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

/**
 * User-friendly form to create consent requests
 */

$consentUrls = [];
$error = '';
$success = '';
$processedCount = 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['phone'])) {
    $phoneInput = $_POST['phone'];
    
    // Split by comma and process each phone number
    $phoneNumbers = array_map('trim', explode(',', $phoneInput));
    $phoneNumbers = array_filter($phoneNumbers); // Remove empty entries
    
    if (empty($phoneNumbers)) {
        $error = 'Please enter at least one phone number';
    } else {
        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);
            
            $baseUrl = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]" . dirname($_SERVER['PHP_SELF']);
            
            foreach ($phoneNumbers as $phone) {
                // Auto-format phone number - remove all non-numeric characters first
                $numbersOnly = preg_replace('/[^0-9]/', '', $phone);
                
                // Validate that we have 10 or 11 digits
                if (strlen($numbersOnly) < 10 || strlen($numbersOnly) > 11) {
                    $error .= "Invalid phone number: " . htmlspecialchars($phone) . " (must have 10-11 digits)\n";
                    continue;
                }
                
                // Format to E.164 format
                if (strlen($numbersOnly) === 10) {
                    $formattedPhone = '+1' . $numbersOnly;
                } else {
                    $formattedPhone = '+' . $numbersOnly;
                }
                
                // 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([$formattedPhone, $token, $_SERVER['REMOTE_ADDR'] ?? 'Unknown', $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown']);
                
                // Generate consent URL
                $consentUrl = $baseUrl . "/consent_simple.php?token=" . urlencode($token) . "&phone=" . urlencode($formattedPhone);
                
                $consentUrls[] = [
                    'original' => $phone,
                    'formatted' => $formattedPhone,
                    'url' => $consentUrl
                ];
                
                $processedCount++;
            }
            
            if ($processedCount > 0) {
                $success = "Successfully created {$processedCount} consent request(s)!";
            }
            
        } catch (Exception $e) {
            $error = "Error: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create SMS Consent Request</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h4>Create SMS Consent Request</h4>
                    </div>
                    <div class="card-body">
                        <?php if ($error): ?>
                            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
                        <?php endif; ?>
                        
                        <?php if ($success): ?>
                            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
                        <?php endif; ?>
                        
                        <?php if (!empty($consentUrls)): ?>
                            <div class="alert alert-info">
                                <h5>Consent URLs Generated:</h5>
                                <?php foreach ($consentUrls as $consent): ?>
                                    <div class="mb-3 p-3 border rounded">
                                        <p class="mb-1"><strong>Original:</strong> <?php echo htmlspecialchars($consent['original']); ?></p>
                                        <p class="mb-1"><strong>Formatted:</strong> <?php echo htmlspecialchars($consent['formatted']); ?></p>
                                        <p class="mb-2"><strong>URL:</strong> <a href="<?php echo htmlspecialchars($consent['url']); ?>" target="_blank"><?php echo htmlspecialchars($consent['url']); ?></a></p>
                                        <a href="<?php echo htmlspecialchars($consent['url']); ?>" class="btn btn-sm btn-primary" target="_blank">
                                            Test Consent Page
                                        </a>
                                    </div>
                                <?php endforeach; ?>
                                <hr>
                                <p class="mb-0"><strong>Next Steps:</strong></p>
                                <ol class="mb-0">
                                    <li>Send these URLs to users via SMS or email</li>
                                    <li>Users will visit URLs to approve/deny consent</li>
                                    <li>Check admin panel to manage consent requests</li>
                                </ol>
                            </div>
                            <div class="text-center mt-3">
                                <a href="admin_consent.php?admin=Homiez@420" class="btn btn-secondary">
                                    Admin Panel
                                </a>
                            </div>
                        <?php endif; ?>
                        
                        <form method="POST">
                            <div class="mb-3">
                                <label for="phone" class="form-label">Phone Numbers (comma-separated)</label>
                                <textarea class="form-control" id="phone" name="phone" rows="3" 
                                          placeholder="(123) 456-7890, +19876543210, 555-123-4567" 
                                          required><?php echo htmlspecialchars($_POST['phone'] ?? ''); ?></textarea>
                                <div class="form-text">Enter multiple phone numbers separated by commas. Any format accepted - will be auto-formatted to E.164 format.</div>
                            </div>
                            <div class="text-center">
                                <button type="submit" class="btn btn-success">Create Consent Request(s)</button>
                                <a href="admin_consent.php?admin=Homiez@420" class="btn btn-outline-secondary">View Admin Panel</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>