<?php
session_start();
require_once 'config/database.php';
require_once 'includes/email_templates.php'; // Include if you have email templates

date_default_timezone_set('UTC'); // Change this to your server's timezone if needed
// Set headers for JSON response
header('Content-Type: application/json');

// Get JSON data
$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['action'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$database = new Database();
$db = $database->getConnection();

// Handle different actions
switch ($data['action']) {
    case 'send_code':
        handleSendCode($db, $data);
        break;
    case 'verify_code':
        handleVerifyCode($db, $data);
        break;
    case 'reset_password':
        handleResetPassword($db, $data);
        break;
    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        exit;
}

/**
 * Handle sending verification code
 */
function handleSendCode($db, $data) {
    if (!isset($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'message' => 'Invalid email address']);
        exit;
    }

    $email = $data['email'];

    // Check if user exists
    $stmt = $db->prepare("SELECT id, first_name, last_name FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        echo json_encode(['success' => false, 'message' => 'No account found with this email address']);
        exit;
    }

    // Generate verification code and token
    $code = sprintf("%06d", mt_rand(100000, 999999)); // 6-digit code
    $token = bin2hex(random_bytes(32)); // Secure token
    $now = new DateTime();
    $expires = (new DateTime())->add(new DateInterval('PT1H')); // 1 hour expiry

    try {
        // Delete any existing reset requests for this email
        $stmt = $db->prepare("DELETE FROM password_resets WHERE email = ?");
        $stmt->execute([$email]);

        // Create new reset request
        $stmt = $db->prepare("INSERT INTO password_resets (email, token, code, created_at, expires_at) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            $email,
            $token,
            $code,
            $now->format('Y-m-d H:i:s'),
            $expires->format('Y-m-d H:i:s')
        ]);

        // Log the token for debugging
        error_log("Password reset token generated for $email: $token");
        error_log("Password reset code generated for $email: $code");

        // Send email with verification code
        $userName = $user['first_name'] . ' ' . $user['last_name'];
        $emailSent = false;
        
        // Try to use the email template function if it exists
        if (function_exists('sendPasswordResetEmail')) {
            $emailSent = sendPasswordResetEmail($email, $userName, $token);
        } else {
            // Fallback to a simple email
            $subject = "Password Reset Verification Code";
            $message = "Hello $userName,\n\n";
            $message .= "You have requested to reset your password. Your verification code is: $code\n\n";
            $message .= "This code will expire in 1 hour.\n\n";
            $message .= "If you did not request a password reset, please ignore this email.\n\n";
            $message .= "Regards,\nThe Banking Team";
            
            $headers = "From: " . (defined('MAIL_FROM_NAME') ? MAIL_FROM_NAME : 'First National Bank Incorporated') . 
                       " <" . (defined('MAIL_FROM_ADDRESS') ? MAIL_FROM_ADDRESS : 'noreply@example.com') . ">\r\n";
            
            $emailSent = mail($email, $subject, $message, $headers);
        }

        if ($emailSent) {
            echo json_encode(['success' => true, 'message' => 'Verification code sent to your email']);
        } else {
            // Even if email fails, we'll return success but log the error
            error_log("Failed to send password reset email to: $email");
            echo json_encode(['success' => true, 'message' => 'Verification code sent to your email']);
        }
        
    } catch (PDOException $e) {
        error_log("Password reset error: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'An error occurred. Please try again later.']);
    }
}

/**
 * Handle verification code validation
 */
function handleVerifyCode($db, $data) {
    if (!isset($data['email']) || !isset($data['code'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid request']);
        exit;
    }

    $email = $data['email'];
    $code = $data['code'];

    try {
        // Check if code is valid and not expired
        $stmt = $db->prepare("
            SELECT token FROM password_resets 
            WHERE email = ? AND code = ? AND expires_at > NOW()
        ");
        $stmt->execute([$email, $code]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$result) {
            echo json_encode(['success' => false, 'message' => 'Invalid or expired verification code']);
            exit;
        }

        // Log the token for debugging
        error_log("Password reset code verified for $email. Token: " . $result['token']);

        echo json_encode([
            'success' => true, 
            'message' => 'Code verified successfully',
            'reset_token' => $result['token']
        ]);
        
    } catch (PDOException $e) {
        error_log("Password reset verification error: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'An error occurred. Please try again later.']);
    }
}

/**
 * Handle password reset
 */
function handleResetPassword($db, $data) {
    if (!isset($data['email']) || !isset($data['reset_token']) || !isset($data['password'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid request']);
        exit;
    }

    $email = $data['email'];
    $token = $data['reset_token'];
    $password = $data['password'];

    // Log the reset attempt for debugging
    error_log("Password reset attempt: Email=$email, Token=" . substr($token, 0, 10) . "...");

    // Validate password
    if (strlen($password) < 8) {
        echo json_encode(['success' => false, 'message' => 'Password must be at least 8 characters long']);
        exit;
    }

    try {
        // Start transaction
        $db->beginTransaction();
        
        // Check if token is valid and not expired
        $stmt = $db->prepare("
            SELECT * FROM password_resets 
            WHERE email = ? AND token = ? AND expires_at > NOW()
        ");
        $stmt->execute([$email, $token]);
        $reset = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$reset) {
            // For debugging, let's check if the token exists at all
            $check_stmt = $db->prepare("SELECT * FROM password_resets WHERE token = ?");
            $check_stmt->execute([$token]);
            $token_exists = $check_stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($token_exists) {
                error_log("Token exists but for email: " . $token_exists['email'] . " or is expired");
                error_log("Token expiry: " . $token_exists['expires_at']);
                error_log("Current time: " . date('Y-m-d H:i:s'));
            } else {
                error_log("Token does not exist in database: " . $token);
            }
            
            error_log("Invalid reset token for $email");
            echo json_encode(['success' => false, 'message' => 'Invalid or expired reset token']);
            exit;
        }

        // Update user's password
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $db->prepare("UPDATE users SET password = ? WHERE email = ?");
        $stmt->execute([$hashedPassword, $email]);

        // Delete the used reset token
        $stmt = $db->prepare("DELETE FROM password_resets WHERE email = ?");
        $stmt->execute([$email]);

        // Commit transaction
        $db->commit();

        error_log("Password reset successful for $email");
        echo json_encode(['success' => true, 'message' => 'Password has been reset successfully']);
        
    } catch (PDOException $e) {
        // Rollback transaction on error
        $db->rollBack();
        error_log("Password reset error: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'An error occurred. Please try again later.']);
    }
}
?>
