<?php
session_start();
include('../includes/config.php');

header('Content-Type: application/json');

$password = isset($_POST['password']) ? $_POST['password'] : '';

if (empty($password)) {
    echo json_encode(array('success' => false, 'message' => 'Password is required'));
    exit();
}

// Get admin password from database
$admin_id = $_SESSION['admin_id'] ?: 1;
$admin_sql = "SELECT password FROM admins WHERE id = $admin_id";
$admin_result = mysqli_query($conn, $admin_sql);

if (mysqli_num_rows($admin_result) > 0) {
    $admin_row = mysqli_fetch_assoc($admin_result);
    $stored_password = $admin_row['password'];
    
    // Check password (using md5 to match your existing auth)
    $input_password_md5 = md5($password);
    
    if ($input_password_md5 === $stored_password) {
        // Password is correct - unlock session
        unset($_SESSION['locked']);
        $_SESSION['last_activity'] = time();
        
        // Log the unlock activity
        $admin_name = $_SESSION['admin_name'] ?: 'Unknown';
        $ip_address = $_SERVER['REMOTE_ADDR'] ?: '';
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?: '';
        
        $log_sql = "INSERT INTO admin_activities (admin_id, admin_name, admin_role, action, description, module, ip_address, user_agent, created_at) 
                    VALUES ('$admin_id', '$admin_name', 'admin', 'Session Unlocked', 
                    'Admin unlocked session from lock screen', 
                    'Security', '$ip_address', '$user_agent', NOW())";
        mysqli_query($conn, $log_sql);
        
        echo json_encode(array('success' => true, 'message' => 'Access granted'));
    } else {
        // Wrong password
        echo json_encode(array('success' => false, 'message' => 'Incorrect password'));
    }
} else {
    // Admin not found
    echo json_encode(array('success' => false, 'message' => 'Admin account not found'));
}
?>