<?php
// Upgrade Contacts Table for Admin Support
require_once '../config.php';

echo "<h2>Upgrading Contacts Schema...</h2>";

try {
    $conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 1. Add owner_type and owner_id columns if not exist
    $columns = $conn->query("SHOW COLUMNS FROM contacts")->fetchAll(PDO::FETCH_COLUMN);

    if (!in_array('owner_type', $columns)) {
        echo "Adding 'owner_type' column...<br>";
        $conn->exec("ALTER TABLE contacts ADD COLUMN owner_type ENUM('user', 'admin') NOT NULL DEFAULT 'user' AFTER id");
    }

    if (!in_array('owner_id', $columns)) {
        echo "Adding 'owner_id' column...<br>";
        $conn->exec("ALTER TABLE contacts ADD COLUMN owner_id INT NOT NULL DEFAULT 0 AFTER owner_type");
        // Update existing rows: Copy user_id to owner_id
        $conn->exec("UPDATE contacts SET owner_id = user_id WHERE owner_type = 'user'");
    }

    // 2. Drop old User-only Unique Index if exists
    // We previously created 'unique_user_contact' on (user_id, phone_number)
    try {
        $conn->exec("ALTER TABLE contacts DROP INDEX unique_user_contact");
        echo "Dropped old unique index.<br>";
    } catch (Exception $e) { /* Ignore */
    }

    // 3. Create NEW Unique Index on (owner_type, owner_id, phone_number)
    try {
        $conn->exec("ALTER TABLE contacts ADD CONSTRAINT unique_owner_contact UNIQUE (owner_type, owner_id, phone_number)");
        echo "Created new unique index (owner_type, owner_id, phone).<br>";
    } catch (Exception $e) { /* Ignore */
    }

    // 4. Make user_id nullable or remove it?
    // user_id is legacy now, but let's keep it nullable for backward compat if needed, or just ignore it.
    // Actually, let's keep it but make it nullable so Admin entries (where user_id is meaningless) don't fail.
    $conn->exec("ALTER TABLE contacts MODIFY COLUMN user_id INT NULL");

    echo "<h3 style='color: green;'>&#10004; Schema Upgrade Complete!</h3>";
    echo "<p>Contacts table now supports both Admin and User ownership.</p>";

} catch (PDOException $e) {
    echo "<h3 style='color: red;'>&#10008; Error: " . $e->getMessage() . "</h3>";
}
?>