<?php
require_once '../config/headers.php';
require_once '../config/database.php';
require_once '../utils/response.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, 'error', 'Method not allowed');
}

$data = json_decode(file_get_contents("php://input"));

if (empty($data->email) || empty($data->otp) || empty($data->new_password)) {
    sendResponse(400, 'error', 'Missing required fields');
}

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

try {
    // Verify OTP one last time for security before changing password
    $stmt = $db->prepare("SELECT id, otp_expires_at FROM admins WHERE email = :email AND reset_otp = :otp LIMIT 1");
    $stmt->execute(['email' => $data->email, 'otp' => $data->otp]);
    
    if ($stmt->rowCount() > 0) {
        $admin = $stmt->fetch();
        
        if (strtotime($admin['otp_expires_at']) < time()) {
            sendResponse(400, 'error', 'OTP has expired');
        }

        // Hash the new password
        $hashed_password = password_hash($data->new_password, PASSWORD_BCRYPT);

        // Update password and clear OTP fields
        $updateStmt = $db->prepare("UPDATE admins SET password_hash = :password, reset_otp = NULL, otp_expires_at = NULL WHERE id = :id");
        $updateStmt->execute([
            'password' => $hashed_password,
            'id' => $admin['id']
        ]);

        sendResponse(200, 'success', 'Password reset successfully');
    } else {
        sendResponse(400, 'error', 'Invalid request');
    }
} catch (PDOException $e) {
    sendResponse(500, 'error', 'Database error occurred');
}
?>