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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

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

$email = isset($data['email']) ? trim($data['email']) : '';
$password = isset($data['password']) ? trim($data['password']) : '';

error_log("Admin login attempt - Email: $email");

// Validate inputs
if (empty($email) || empty($password)) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Email and password are required']);
    exit;
}

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid email format']);
    exit;
}

// Query for admin user from admins table
$stmt = $conn->prepare("SELECT id, name, email, password, phone, position, permission_level, status FROM admins WHERE email = ? AND status = 'active' LIMIT 1");

if (!$stmt) {
    error_log("Prepare failed: " . $conn->error);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Database error']);
    exit;
}

$stmt->bind_param('s', $email);

if (!$stmt->execute()) {
    error_log("Execute failed: " . $stmt->error);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Database error']);
    exit;
}

$result = $stmt->get_result();
$admin = $result->fetch_assoc();

if (!$admin) {
    error_log("Admin user not found: $email");
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Admin account not found or invalid credentials']);
    exit;
}

// Verify password
if (!password_verify($password, $admin['password'])) {
    error_log("Invalid password for admin: $email");
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid email or password']);
    exit;
}

// Set session variables
$_SESSION['admin_id'] = $admin['id'];
$_SESSION['admin_email'] = $admin['email'];
$_SESSION['admin_name'] = $admin['name'];
$_SESSION['admin_position'] = $admin['position'];
$_SESSION['admin_permission'] = $admin['permission_level'];
$_SESSION['admin_phone'] = $admin['phone'];

// Also set admin_user for auth_check compatibility
$_SESSION['admin_user'] = [
    'id' => $admin['id'],
    'name' => $admin['name'],
    'email' => $admin['email'],
    'phone' => $admin['phone'],
    'position' => $admin['position'],
    'permission_level' => $admin['permission_level']
];

// Update last login time
$updateStmt = $conn->prepare("UPDATE admins SET last_login = NOW() WHERE id = ?");
$updateStmt->bind_param('i', $admin['id']);
$updateStmt->execute();
$updateStmt->close();

// Generate a token (optional - for API requests)
$token = bin2hex(random_bytes(32));
$_SESSION['admin_token'] = $token;

error_log("Admin login successful - ID: " . $admin['id'] . ", Email: " . $admin['email']);

// Return success response
header('Content-Type: application/json');
echo json_encode([
    'success' => true,
    'message' => 'Login successful',
    'data' => [
        'id' => $admin['id'],
        'name' => $admin['name'],
        'email' => $admin['email'],
        'phone' => $admin['phone'],
        'position' => $admin['position'],
        'permission_level' => $admin['permission_level']
    ],
    'token' => $token
]);

$stmt->close();
$conn->close();
?>

