<?php
require_once 'vendor/autoload.php';
require_once 'config.php';

/**
 * Create a consent request for any phone number
 * Usage: create_consent.php?phone=+1234567890
 */

if (!isset($_GET['phone'])) {
    die("Error: Phone number required. Usage: create_consent.php?phone=+1234567890");
}

$phone = $_GET['phone'];

// Validate phone number format
if (!preg_match('/^\+\d{10,15}$/', $phone)) {
    die("Error: Invalid phone number format. Use format: +1234567890");
}

try {
    // Connect to database
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];
    $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
    
    // Generate unique token
    $token = bin2hex(random_bytes(16));
    
    // Insert consent request
    $sql = "INSERT INTO consent_requests 
            (phone_number, consent_token, consent_status, ip_address, user_agent)
            VALUES (?, ?, 'pending', ?, ?)
            ON DUPLICATE KEY UPDATE 
            consent_token = VALUES(consent_token),
            consent_status = 'pending',
            request_date = CURRENT_TIMESTAMP";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$phone, $token, $_SERVER['REMOTE_ADDR'] ?? 'Unknown', $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown']);
    
    // Generate consent URL (SMS links require absolute URLs)
    $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? "https" : "http") . "://" . ($_SERVER['HTTP_HOST'] ?? 'localhost');
    $scriptDir = dirname($_SERVER['PHP_SELF']);
    $pathPrefix = $scriptDir === '/' ? '' : rtrim($scriptDir, '/');
    $consentUrl = $baseUrl . $pathPrefix . "/consent_simple.php?token=" . urlencode($token) . "&phone=" . urlencode($phone);
    
    echo "Consent request created successfully!<br><br>";
    echo "<strong>Phone:</strong> $phone<br>";
    echo "<strong>Token:</strong> $token<br>";
    echo "<strong>Consent URL:</strong> <a href='$consentUrl' target='_blank'>$consentUrl</a><br><br>";
    
    // Instructions for sending SMS
    echo "<strong>Next Steps:</strong><br>";
    echo "1. Send this URL to the user via SMS: $consentUrl<br>";
    echo "2. User will visit the URL and approve/deny consent<br>";
    echo "3. Check database for consent status<br><br>";
    
    echo "<small>Note: To send SMS automatically, integrate with Twilio SMS API in your application.</small>";
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>
