<?php
require_once 'config.php';

/**
 * Twilio Webhook Handler
 * Handles incoming SMS responses for consent management
 */

header('Content-Type: text/xml');

// Handle GET requests (when accessing webhook directly in browser)
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo createTwilioResponse("This is the Twilio webhook endpoint for Mark's Tech Solution SMS consent management. This endpoint handles incoming SMS responses automatically.");
    exit;
}

// Only allow POST requests for actual webhook processing
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo createTwilioResponse("Method not allowed. This endpoint only accepts POST requests from Twilio.");
    exit;
}

try {
    // Get incoming SMS data
    $from = $_POST['From'] ?? '';
    $body = strtolower(trim($_POST['Body'] ?? ''));
    $messageSid = $_POST['MessageSid'] ?? '';
    
    if (empty($from) || empty($body)) {
        throw new Exception('Missing required parameters');
    }
    
    // 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);
    
    // Find pending consent request for this phone number
    $sql = "SELECT * FROM consent_requests 
            WHERE phone_number = ? AND consent_status = 'pending' 
            ORDER BY request_date DESC LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$from]);
    $consent = $stmt->fetch();
    
    if (!$consent) {
        // No pending consent found
        $responseMessage = "No pending consent request found. Please contact Mark's Tech Solution at (339) 245-2270 for assistance.";
        echo createTwilioResponse($responseMessage);
        exit;
    }
    
    // Process the response
    $response = '';
    $status = '';
    
    if (in_array($body, ['yes', 'y', 'approve', 'accepted', 'agree'])) {
        $status = 'approved';
        $response = "Thank you! You have successfully opted in to receive SMS messages from Mark's Tech Solution. Reply STOP at any time to unsubscribe.";
    } elseif (in_array($body, ['no', 'n', 'deny', 'decline', 'stop'])) {
        $status = 'denied';
        $response = "You have opted out of SMS messages from Mark's Tech Solution. If you change your mind, please contact us at (339) 245-2270.";
    } else {
        // Unrecognized response
        $response = "Please reply YES to approve or NO to deny SMS messages from Mark's Tech Solution.";
        echo createTwilioResponse($response);
        exit;
    }
    
    // Update consent status
    $sql = "UPDATE consent_requests 
            SET consent_status = ?, response_date = CURRENT_TIMESTAMP
            WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$status, $consent['id']]);
    
    // Log the message
    $sql = "INSERT INTO message_logs 
            (consent_id, phone_number, message_sid, message_content, message_type, status)
            VALUES (?, ?, ?, ?, 'consent_response', 'received')";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$consent['id'], $from, $messageSid, "User response: {$body}"]);
    
    // Log revocation if denied
    if ($status === 'denied') {
        $sql = "INSERT INTO consent_revocations 
                (consent_id, phone_number, revocation_reason, ip_address, user_agent)
                VALUES (?, ?, 'User denied consent via SMS', NULL, 'SMS Response')";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$consent['id'], $from]);
    }
    
    // Send confirmation response
    echo createTwilioResponse($response);
    
} catch (Exception $e) {
    // Log error
    error_log("Twilio webhook error: " . $e->getMessage());
    
    // Send error response
    $errorResponse = "Sorry, there was an error processing your response. Please contact Mark's Tech Solution at (339) 245-2270.";
    echo createTwilioResponse($errorResponse);
}

/**
 * Create Twilio TwiML response
 */
function createTwilioResponse($message) {
    $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    $xml .= '<Response>' . "\n";
    $xml .= '    <Message>' . htmlspecialchars($message, ENT_XML1, 'UTF-8') . '</Message>' . "\n";
    $xml .= '</Response>';
    return $xml;
}
?>
