<?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 files exist
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;
}

if (!file_exists('mail_config.php')) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Mail 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'] ?? '';

// Send OTP for signup
if ($action === 'send_signup_otp') {
    $email = trim($data['email'] ?? '');
    $name = trim($data['name'] ?? '');
    $phone = trim($data['phone'] ?? '');
    $password = $data['password'] ?? '';
    $confirmPassword = $data['confirmPassword'] ?? '';

    // Validate input
    if (!$email || !$name || !$phone || !$password || !$confirmPassword) {
        sendResponse(false, 'All fields are required');
    }

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        sendResponse(false, 'Invalid email format');
    }

    // Validate phone format (basic check)
    if (!preg_match('/^[0-9]{10}$/', preg_replace('/[^0-9]/', '', $phone))) {
        sendResponse(false, 'Invalid phone number format');
    }

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

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

    // Check if email already exists
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    if ($stmt->get_result()->num_rows > 0) {
        sendResponse(false, 'Email already registered');
    }
    $stmt->close();

    // Check if email already has a pending registration
    $stmt = $conn->prepare("SELECT id FROM pending_registrations WHERE email = ? AND is_verified = 0 AND expires_at > NOW()");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    if ($stmt->get_result()->num_rows > 0) {
        sendResponse(false, 'OTP already sent to this email. Please check your inbox.');
    }
    $stmt->close();

    // Generate OTP
    $otp = generateOTP();

    // Send email with OTP
    $mailResult = sendEmailWithOTP($email, $otp, 'signup');
    if (!$mailResult['success']) {
        sendResponse(false, 'Failed to send OTP: ' . $mailResult['message']);
    }

    // Store pending registration
    $hashedPassword = hashPassword($password);
    $stmt = $conn->prepare("INSERT INTO pending_registrations (name, email, phone, password, otp_code) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("sssss", $name, $email, $phone, $hashedPassword, $otp);

    if ($stmt->execute()) {
        sendResponse(true, 'OTP sent successfully to ' . $email . '. Please check your inbox.', [
            'email' => $email
        ]);
    } else {
        sendResponse(false, 'Error creating pending registration: ' . $conn->error);
    }

    $stmt->close();
}

// Send OTP for password reset
elseif ($action === 'send_reset_otp') {
    $email = trim($data['email'] ?? '');

    // Validate email
    if (!$email) {
        sendResponse(false, 'Email is required');
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        sendResponse(false, 'Invalid email format');
    }

    // Check if email exists in users table
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    if ($stmt->get_result()->num_rows === 0) {
        // Don't reveal if email exists or not for security reasons
        sendResponse(true, 'If an account exists with this email, you will receive an OTP shortly.', [
            'email' => $email
        ]);
        $stmt->close();
        exit;
    }
    $stmt->close();

    // Check if there's an existing reset request that hasn't expired
    $stmt = $conn->prepare("SELECT id FROM password_resets WHERE email = ? AND is_verified = 0 AND expires_at > NOW()");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    if ($stmt->get_result()->num_rows > 0) {
        sendResponse(false, 'An OTP has already been sent to this email. Please check your inbox or wait for it to expire.');
    }
    $stmt->close();

    // Generate OTP and token
    $otp = generateOTP();
    $token = bin2hex(random_bytes(50));

    // Send email with OTP
    $mailResult = sendEmailWithOTP($email, $otp, 'password_reset');
    if (!$mailResult['success']) {
        sendResponse(false, 'Failed to send OTP: ' . $mailResult['message']);
    }

    // Store password reset request
    $stmt = $conn->prepare("INSERT INTO password_resets (email, token, otp) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $email, $token, $otp);

    if ($stmt->execute()) {
        sendResponse(true, 'OTP sent successfully to ' . $email . '. Please check your inbox.', [
            'email' => $email,
            'token' => $token
        ]);
    } else {
        sendResponse(false, 'Error creating password reset request: ' . $conn->error);
    }

    $stmt->close();
}

// Resend OTP
elseif ($action === 'resend_otp') {
    $email = trim($data['email'] ?? '');
    $purpose = $data['purpose'] ?? 'signup'; // 'signup' or 'password_reset'
    if ($purpose === 'reset') {
        $purpose = 'password_reset';
    }

    if (!$email) {
        sendResponse(false, 'Email is required');
    }

    // Check rate limiting - only allow resend after 30 seconds
    if ($purpose === 'signup') {
        $stmt = $conn->prepare("SELECT created_at FROM pending_registrations WHERE email = ? AND is_verified = 0 ORDER BY created_at DESC LIMIT 1");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $lastOtpTime = strtotime($row['created_at']);
            if (time() - $lastOtpTime < 30) {
                sendResponse(false, 'Please wait 30 seconds before requesting a new OTP');
            }
        }
        $stmt->close();
    }

    // Generate new OTP
    $otp = generateOTP();

    // Send email
    $mailResult = sendEmailWithOTP($email, $otp, $purpose);
    if (!$mailResult['success']) {
        sendResponse(false, 'Failed to send OTP: ' . $mailResult['message']);
    }

    // Update OTP in database
    if ($purpose === 'signup') {
        $stmt = $conn->prepare("UPDATE pending_registrations SET otp_code = ?, attempts = 0, created_at = NOW() WHERE email = ? AND is_verified = 0");
        $stmt->bind_param("ss", $otp, $email);
    } else {
        $stmt = $conn->prepare("UPDATE password_resets SET otp = ?, attempts = 0, created_at = NOW() WHERE email = ? AND is_verified = 0");
        $stmt->bind_param("ss", $otp, $email);
    }

    if ($stmt->execute()) {
        sendResponse(true, 'OTP resent successfully to ' . $email, [
            'email' => $email
        ]);
    } else {
        sendResponse(false, 'Error resending OTP: ' . $conn->error);
    }

    $stmt->close();
}

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

$conn->close();
?>
