<?php
/**
 * Save Response - save_response.php
 * Backend script to handle form submission
 * Stores response in database and sends email notification
 */

require_once 'config.php';

header('Content-Type: application/json');

try {
    // Get form data
    $response = isset($_POST['response']) ? sanitize($_POST['response']) : '';
    $name = isset($_POST['name']) ? sanitize($_POST['name']) : 'Unknown';
    $ip_address = getClientIP();
    $timestamp = date('Y-m-d H:i:s');
    
    // Validate response
    if ($response !== 'YES') {
        throw new Exception('Invalid response');
    }
    
    // Connect to database
    $pdo = getDBConnection();
    
    // Insert into database
    $stmt = $pdo->prepare('
        INSERT INTO responses (name, response, ip_address, timestamp)
        VALUES (:name, :response, :ip_address, :timestamp)
    ');
    
    $stmt->execute([
        ':name' => $name,
        ':response' => $response,
        ':ip_address' => $ip_address,
        ':timestamp' => $timestamp
    ]);
    
    // Send email notification
    sendYESNotification($name, $timestamp, $ip_address);
    
    // Redirect to success page
    header('Location: success.php');
    exit;
    
} catch (Exception $e) {
    error_log('Error saving response: ' . $e->getMessage());
    header('HTTP/1.1 500 Internal Server Error');
    echo json_encode(['error' => 'Failed to save response']);
    exit;
}
?>
