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

/**
 * Automatic consent request with SMS sending
 */

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['phone'])) {
    $phone = $_POST['phone'];
    
    // Validate phone number
    if (!preg_match('/^\+?[0-9\s\-\(\)]{10,15}$/', $phone)) {
        die(json_encode(['success' => false, 'error' => 'Invalid phone number']));
    }
    
    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);
        
        // Format phone number
        $numbersOnly = preg_replace('/[^0-9]/', '', $phone);
        if (strlen($numbersOnly) === 10) {
            $formattedPhone = '+1' . $numbersOnly;
        } elseif (strlen($numbersOnly) === 11 && substr($numbersOnly, 0, 1) === '1') {
            $formattedPhone = '+' . $numbersOnly;
        } else {
            $formattedPhone = '+' . $numbersOnly;
        }
        
        // Generate 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'] ?? 'API', 'Auto Consent']);
        
        // 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($formattedPhone);
        
        // Send SMS with consent URL
        $twilio = new Twilio\Rest\Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);
        
        $message = $twilio->messages->create(
            $formattedPhone,
            [
                'from' => TWILIO_PHONE_NUMBER,
                'body' => "Mark's Tech Solution: Please approve SMS messaging consent: " . $consentUrl . " Reply STOP to opt out."
            ]
        );
        
        // Log the message
        $sql = "INSERT INTO message_logs 
                (consent_id, phone_number, message_sid, message_content, message_type, status)
                VALUES ((SELECT id FROM consent_requests WHERE consent_token = ?), ?, ?, ?, 'consent_request', 'sent')";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$token, $formattedPhone, $message->sid, "Consent request sent via SMS"]);
        
        echo json_encode([
            'success' => true,
            'message' => 'Consent request sent via SMS',
            'phone' => $formattedPhone,
            'consent_url' => $consentUrl,
            'message_sid' => $message->sid
        ]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Auto Send 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>Auto Send Consent Request</h4>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <h5>How it works:</h5>
                            <ol>
                                <li>Enter customer phone number</li>
                                <li>System automatically sends SMS with consent link</li>
                                <li>Customer clicks link to approve/deny</li>
                                <li>Check admin panel for consent status</li>
                            </ol>
                        </div>
                        
                        <form id="autoConsentForm">
                            <div class="mb-3">
                                <label for="phone" class="form-label">Phone Number</label>
                                <input type="text" class="form-control" id="phone" name="phone" 
                                       placeholder="+1234567890 or (123) 456-7890" required>
                                <div class="form-text">Customer will receive SMS with consent link</div>
                            </div>
                            <div class="text-center">
                                <button type="submit" class="btn btn-primary">
                                    <span class="spinner-border spinner-border-sm d-none" id="loading"></span>
                                    Send Consent Request
                                </button>
                                <a href="admin_consent.php?admin=Homiez@420" class="btn btn-outline-secondary">
                                    Admin Panel
                                </a>
                            </div>
                        </form>
                        
                        <div id="result" class="mt-3"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('autoConsentForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const phone = document.getElementById('phone').value;
            const loading = document.getElementById('loading');
            const result = document.getElementById('result');
            
            loading.classList.remove('d-none');
            result.innerHTML = '';
            
            fetch('auto_consent.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    phone: phone
                })
            })
            .then(response => response.json())
            .then(data => {
                loading.classList.add('d-none');
                
                if (data.success) {
                    result.innerHTML = `
                        <div class="alert alert-success">
                            <h6>✅ Consent Request Sent!</h6>
                            <p><strong>To:</strong> ${data.phone}</p>
                            <p><strong>Message SID:</strong> ${data.message_sid}</p>
                            <p><strong>Consent URL:</strong> <a href="${data.consent_url}" target="_blank">${data.consent_url}</a></p>
                        </div>
                    `;
                } else {
                    result.innerHTML = `
                        <div class="alert alert-danger">
                            <h6>❌ Error:</h6>
                            <p>${data.error}</p>
                        </div>
                    `;
                }
            })
            .catch(error => {
                loading.classList.add('d-none');
                result.innerHTML = `
                    <div class="alert alert-danger">
                        <h6>❌ Network Error:</h6>
                        <p>${error.message}</p>
                    </div>
                `;
            });
        });
    </script>
</body>
</html>