<?php
// Enable error logging
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Set error handler to catch errors and return JSON
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Server error occurred',
        'error_detail' => $errstr . ' in ' . $errfile . ':' . $errline
    ]);
    exit;
});

session_start();

// Check if config file exists
if (!file_exists('config.php')) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Configuration file not found']);
    exit;
}

include 'config.php';
include 'mail_config.php';

// Verify connection exists
if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Invalid request method');
}

$data = json_decode(file_get_contents("php://input"), true);
$action = $data['action'] ?? '';

// Verify signup OTP
if ($action === 'verify_signup_otp') {
    $email = trim($data['email'] ?? '');
    $otp = trim($data['otp'] ?? '');

    if (!$email || !$otp) {
        sendResponse(false, 'Email and OTP are required');
    }

    // Validate OTP format
    if (!preg_match('/^[0-9]{6}$/', $otp)) {
        sendResponse(false, 'OTP must be 6 digits');
    }

    // Find pending registration
    $stmt = $conn->prepare("SELECT id, name, email, phone, password, otp_code, attempts, expires_at FROM pending_registrations WHERE email = ? AND is_verified = 0");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        sendResponse(false, 'No pending registration found for this email');
    }

    $pending = $result->fetch_assoc();
    $stmt->close();

    // Check if OTP has expired
    if (strtotime($pending['expires_at']) < time()) {
        // Delete expired pending registration
        $stmt = $conn->prepare("DELETE FROM pending_registrations WHERE id = ?");
        $stmt->bind_param("i", $pending['id']);
        $stmt->execute();
        $stmt->close();
        sendResponse(false, 'OTP has expired. Please sign up again.');
    }

    // Check if max attempts exceeded
    if ($pending['attempts'] >= OTP_MAX_ATTEMPTS) {
        // Delete pending registration after max attempts
        $stmt = $conn->prepare("DELETE FROM pending_registrations WHERE id = ?");
        $stmt->bind_param("i", $pending['id']);
        $stmt->execute();
        $stmt->close();
        sendResponse(false, 'Maximum OTP verification attempts exceeded. Please sign up again.');
    }

    // Verify OTP
    if ($pending['otp_code'] !== $otp) {
        // Increment attempts
        $newAttempts = $pending['attempts'] + 1;
        $stmt = $conn->prepare("UPDATE pending_registrations SET attempts = ? WHERE id = ?");
        $stmt->bind_param("ii", $newAttempts, $pending['id']);
        $stmt->execute();
        $stmt->close();

        $remainingAttempts = OTP_MAX_ATTEMPTS - $newAttempts;
        sendResponse(false, "Invalid OTP. You have {$remainingAttempts} attempts remaining.");
    }

    // OTP is valid, create user account
    $stmt = $conn->prepare("INSERT INTO users (name, email, phone, password, is_email_verified, email_verified_at) VALUES (?, ?, ?, ?, 1, NOW())");
    $stmt->bind_param("ssss", $pending['name'], $pending['email'], $pending['phone'], $pending['password']);

    if (!$stmt->execute()) {
        // Check if duplicate email error
        if ($conn->errno === 1062) {
            sendResponse(false, 'Email already registered');
        }
        sendResponse(false, 'Error creating account: ' . $conn->error);
    }

    $userId = $conn->insert_id;
    $stmt->close();

    // Delete pending registration after successful verification
    $stmt = $conn->prepare("DELETE FROM pending_registrations WHERE id = ?");
    $stmt->bind_param("i", $pending['id']);
    $stmt->execute();
    $stmt->close();

    // Set session
    $_SESSION['user_id'] = $userId;
    $_SESSION['user_name'] = $pending['name'];
    $_SESSION['user_email'] = $pending['email'];

    sendResponse(true, 'Email verified successfully. Account created!', [
        'id' => $userId,
        'name' => $pending['name'],
        'email' => $pending['email'],
        'phone' => $pending['phone']
    ]);
}

// Verify password reset OTP
elseif ($action === 'verify_reset_otp') {
    $email = trim($data['email'] ?? '');
    $token = trim($data['token'] ?? '');
    $otp = trim($data['otp'] ?? '');
    $newPassword = $data['newPassword'] ?? '';
    $confirmPassword = $data['confirmPassword'] ?? '';

    if (!$email || !$token || !$otp) {
        sendResponse(false, 'Email, token, and OTP are required');
    }

    if (!$newPassword || !$confirmPassword) {
        sendResponse(false, 'New password is required');
    }

    // Validate OTP format
    if (!preg_match('/^[0-9]{6}$/', $otp)) {
        sendResponse(false, 'OTP must be 6 digits');
    }

    // Validate password length
    if (strlen($newPassword) < 6) {
        sendResponse(false, 'Password must be at least 6 characters long');
    }

    // Check if passwords match
    if ($newPassword !== $confirmPassword) {
        sendResponse(false, 'Passwords do not match');
    }

    // Find password reset request
    $stmt = $conn->prepare("SELECT id, email, otp, token, attempts, expires_at FROM password_resets WHERE email = ? AND token = ? AND is_verified = 0");
    $stmt->bind_param("ss", $email, $token);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        sendResponse(false, 'Invalid password reset request');
    }

    $resetRequest = $result->fetch_assoc();
    $stmt->close();

    // Check if request has expired
    if (strtotime($resetRequest['expires_at']) < time()) {
        // Delete expired reset request
        $stmt = $conn->prepare("DELETE FROM password_resets WHERE id = ?");
        $stmt->bind_param("i", $resetRequest['id']);
        $stmt->execute();
        $stmt->close();
        sendResponse(false, 'Password reset request has expired. Please request a new one.');
    }

    // Check if max attempts exceeded
    if ($resetRequest['attempts'] >= PASSWORD_RESET_MAX_ATTEMPTS) {
        // Delete reset request after max attempts
        $stmt = $conn->prepare("DELETE FROM password_resets WHERE id = ?");
        $stmt->bind_param("i", $resetRequest['id']);
        $stmt->execute();
        $stmt->close();
        sendResponse(false, 'Maximum OTP verification attempts exceeded. Please request a new password reset.');
    }

    // Verify OTP
    if ($resetRequest['otp'] !== $otp) {
        // Increment attempts
        $newAttempts = $resetRequest['attempts'] + 1;
        $stmt = $conn->prepare("UPDATE password_resets SET attempts = ? WHERE id = ?");
        $stmt->bind_param("ii", $newAttempts, $resetRequest['id']);
        $stmt->execute();
        $stmt->close();

        $remainingAttempts = PASSWORD_RESET_MAX_ATTEMPTS - $newAttempts;
        sendResponse(false, "Invalid OTP. You have {$remainingAttempts} attempts remaining.");
    }

    // OTP is valid, update user password
    $hashedPassword = hashPassword($newPassword);
    $stmt = $conn->prepare("UPDATE users SET password = ? WHERE email = ?");
    $stmt->bind_param("ss", $hashedPassword, $email);

    if (!$stmt->execute()) {
        sendResponse(false, 'Error updating password: ' . $conn->error);
    }
    $stmt->close();

    // Mark reset request as verified
    $stmt = $conn->prepare("UPDATE password_resets SET is_verified = 1, verified_at = NOW(), reset_at = NOW() WHERE id = ?");
    $stmt->bind_param("i", $resetRequest['id']);
    $stmt->execute();
    $stmt->close();

    sendResponse(true, 'Password reset successfully. Please sign in with your new password.');
}

else {
    sendResponse(false, 'Invalid action');
}

$conn->close();
?>
