<?php
session_start();
header('Content-Type: application/json');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0);

require_once '../../includes/db_connection.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

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

// Validate input
if (!isset($input['username']) || !isset($input['password'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Username and password are required']);
    exit;
}

$username = trim($input['username']);
$password = $input['password'];

// Validate not empty
if (empty($username) || empty($password)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Username and password cannot be empty']);
    exit;
}

try {
    $db = Database::getInstance()->getConnection();
    
    // Debug: Log the incoming request
    error_log("Login attempt for username: " . $username);
    
    // Fetch user from database
    $stmt = $db->prepare("
        SELECT id, username, email, password_hash, full_name, role, is_active 
        FROM admin_users 
        WHERE username = ? 
        LIMIT 1
    ");
    $stmt->execute([$username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Debug: Check if user was found
    if (!$user) {
        error_log("User not found: " . $username);
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Invalid username or password']);
        exit;
    }
    
    error_log("User found: " . $user['username'] . ", Active: " . $user['is_active']);
    
    // Check if user is active
    if ($user['is_active'] != 1) {
        error_log("User account disabled: " . $username);
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Account is disabled. Please contact administrator.']);
        exit;
    }
    
    // Debug: Log password verification attempt
    error_log("Verifying password for: " . $username);
    error_log("Password hash from DB: " . substr($user['password_hash'], 0, 20) . "...");
    
    // Verify password
    $passwordVerified = password_verify($password, $user['password_hash']);
    error_log("Password verification result: " . ($passwordVerified ? 'SUCCESS' : 'FAILED'));
    
    if (!$passwordVerified) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Invalid username or password']);
        exit;
    }
    
    // Update last login
    $updateStmt = $db->prepare("UPDATE admin_users SET last_login = NOW() WHERE id = ?");
    $updateStmt->execute([$user['id']]);
    
    // Create session
    $_SESSION['admin_logged_in'] = true;
    $_SESSION['admin_id'] = $user['id'];
    $_SESSION['admin_username'] = $user['username'];
    $_SESSION['admin_email'] = $user['email'];
    $_SESSION['admin_full_name'] = $user['full_name'];
    $_SESSION['admin_role'] = $user['role'];
    $_SESSION['login_time'] = time();
    
    // Regenerate session ID for security
    session_regenerate_id(true);
    
    error_log("Login successful for: " . $username);
    
    // Return success
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'message' => 'Login successful',
        'user' => [
            'id' => $user['id'],
            'username' => $user['username'],
            'email' => $user['email'],
            'full_name' => $user['full_name'],
            'role' => $user['role']
        ]
    ]);
    
} catch (PDOException $e) {
    error_log('Login database error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error occurred']);
}
?>
