<?php
/**
 * Update User Phone Script (Secure)
 * Run: php scripts/update_phone.php --email=admin@musadaq.com --phone=963992952235
 */

require_once __DIR__ . '/../app/bootstrap/init.php';

use App\Core\Database;
use App\Core\Encryption;

// Parse CLI arguments
$options = getopt("", ["email:", "phone:", "id:"]);
$email = $options['email'] ?? null;
$phone = $options['phone'] ?? null;
$id = $options['id'] ?? null;

if ((!$email && !$id) || !$phone) {
    die("Usage: php scripts/update_phone.php --phone=yourphone [--email=your@email.com | --id=user-uuid]\n");
}

$db = Database::getInstance();

// 1. Sanitize phone
try {
    $cleanPhone = preg_replace('/[^0-9+]/', '', $phone);
    $phoneHash = hash('sha256', $cleanPhone);
    $encryptedPhone = Encryption::encrypt($cleanPhone);

    // 2. Update user
    if ($id) {
        $stmt = $db->prepare("UPDATE users SET phone = ?, phone_hash = ? WHERE id = ?");
        $stmt->execute([$encryptedPhone, $phoneHash, $id]);
        $identifier = "ID $id";
    } else {
        // Note: Searching by encrypted email will likely fail due to IV randomness. Use ID.
        $stmt = $db->prepare("UPDATE users SET phone = ?, phone_hash = ? WHERE email = ?");
        $stmt->execute([$encryptedPhone, $phoneHash, $email]);
        $identifier = "email $email";
    }

    if ($stmt->rowCount() > 0) {
        echo "✅ Success! Phone updated for $identifier\n";
        echo "   Encrypted: $encryptedPhone\n";
        echo "   Hash: $phoneHash\n";
    } else {
        echo "❌ Failed. User with $identifier not found or no changes made.\n";
    }

} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}
