<?php
date_default_timezone_set('Asia/Bahrain');
ini_set('display_errors', 1);
error_reporting(E_ALL);

include_once(__DIR__ . '../../includes/db.php');
header("Content-Type: application/json");



// Log incoming request for debugging.
file_put_contents("otp_debug_output.txt", "[" . date('Y-m-d H:i:s') . "] POST: " . json_encode($_POST) . PHP_EOL, FILE_APPEND);

// === Inputs ===
$action  = $_POST['action'] ?? '';
$input   = trim($_POST['phone_or_email'] ?? '');
$purpose = $_POST['purpose'] ?? '';
$otp     = trim($_POST['otp'] ?? '');  // Trim OTP in case of extra spaces

$email = null;

// === Determine Identifier for OTP ===
if ($purpose === 'signup') {
    // For signup, the input must be a valid email address.
    if (!filter_var($input, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(["status" => false, "message" => "❌ Invalid email format"]);
        exit;
    }
    $email = $input;
} elseif ($purpose === 'reset') {
    // For resets, check if the input is an email; otherwise assume it's a phone number.
    if (strpos($input, '@') !== false) {
        if (!filter_var($input, FILTER_VALIDATE_EMAIL)) {
            echo json_encode(["status" => false, "message" => "❌ Invalid email format"]);
            exit;
        }
        $email = $input;
    } else {
        $digitsOnly = preg_replace('/\D/', '', $input);
        if (substr($digitsOnly, 0, 3) !== '973') {
            $digitsOnly = '973' . $digitsOnly;
        }
        file_put_contents("otp_debug_output.txt", "DEBUG: Normalized phone = $digitsOnly\n", FILE_APPEND);
    
        $user = fetchOne("
            SELECT * FROM users 
            WHERE REPLACE(REPLACE(REPLACE(phone, '+', ''), ' ', ''), '-', '') = ?
        ", [$digitsOnly]);
    
        if (!$user || !isset($user['email']) || !filter_var($user['email'], FILTER_VALIDATE_EMAIL)) {
            echo json_encode(["status" => false, "message" => "❌ No user found for this phone"]);
            exit;
        }
        $email = $user['email'];
    }
} else {
    echo json_encode(["status" => false, "message" => "❌ Invalid purpose"]);
    exit;
}

file_put_contents("otp_debug_output.txt", "DEBUG: Using email = $email\n", FILE_APPEND);

// === Action: Send OTP ===
if ($action === 'send') {
    $existing = fetchOne("SELECT * FROM email_otps WHERE email = ? AND is_verified = 0 AND expires_at > NOW()", [$email]);
    if ($existing) {
        echo json_encode(["status" => false, "message" => "⚠️ OTP already sent. Try again later."]);
        exit;
    }
    
    $otpGenerated = rand(100000, 999999);
    $expiresAt = date('Y-m-d H:i:s', strtotime('+5 minutes'));
    
    file_put_contents("otp_debug_output.txt", "DEBUG: Generated OTP = $otpGenerated, expires at = $expiresAt\n", FILE_APPEND);
    
    $stored = execute(
        "INSERT INTO email_otps (email, otp_code, expires_at, is_verified, created_at) VALUES (?, ?, ?, 0, NOW())",
        [$email, $otpGenerated, $expiresAt]
    );
    
    if (!$stored) {
        echo json_encode(["status" => false, "message" => "❌ Failed to store OTP"]);
        exit;
    }
    
    // --- Load and Process the Email Template ---
    // Path to your email template file (saved as a PHP file so that PHP code is processed).
    $templatePath = __DIR__ . '/../email_templates/otp_email_template.html';
    
    // Use output buffering to capture the included file's output.
    ob_start();
    include $templatePath;
    $htmlContent = ob_get_clean();
    
    // Replace the OTP placeholder with the actual generated OTP.
    $htmlContent = str_replace("{{OTP}}", $otpGenerated, $htmlContent);
    
    // Prepare email headers and subject.
    $subject = "🔐 Your OTP Code";
    $headers = "From: Developer <otp@alhussain-voice.com>\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    
    if (mail($email, $subject, $htmlContent, $headers)) {
        file_put_contents("otp_debug_output.txt", "DEBUG: mail() sent to $email\n", FILE_APPEND);
        echo json_encode([
            "status" => true,
            "message" => "✅ OTP sent to $email",
            "email" => $email
        ]);
    } else {
        file_put_contents("otp_debug_output.txt", "DEBUG: mail() failed to send to $email\n", FILE_APPEND);
        echo json_encode([
            "status" => false,
            "message" => "❌ Failed to send OTP using mail()"
        ]);
    }
    
// === Action: Verify OTP ===
} elseif ($action === 'verify') {
    if (!$otp || !$email) {
        echo json_encode(["status" => false, "message" => "❌ Missing email or OTP"]);
        exit;
    }
    
    file_put_contents("otp_debug_output.txt", "DEBUG: Attempting to verify OTP '$otp' for email '$email'\n", FILE_APPEND);
    
    $row = fetchOne(
        "SELECT * FROM email_otps WHERE email = ? AND otp_code = ? AND is_verified = 0 AND expires_at > NOW()",
        [$email, $otp]
    );
    
    if ($row) {
        file_put_contents("otp_debug_output.txt", "DEBUG: OTP record found: " . print_r($row, true) . "\n", FILE_APPEND);
        execute("UPDATE email_otps SET is_verified = 1 WHERE id = ?", [$row['id']]);
        echo json_encode(["status" => true, "message" => "✅ OTP verified"]);
    } else {
        file_put_contents("otp_debug_output.txt", "DEBUG: OTP verification failed for OTP '$otp' and email '$email'\n", FILE_APPEND);
        echo json_encode(["status" => false, "message" => "❌ Invalid or expired OTP"]);
    }
    
} else {
    echo json_encode(["status" => false, "message" => "❌ Invalid action"]);
}
?>
