<?php
/**
 * Manager Login API
 * Handles manager authentication
 */

session_start();
require 'config.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Only POST method allowed', null);
}

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

if (!isset($data['email']) || !isset($data['password'])) {
    sendResponse(false, 'Email and password are required', null);
}

$email = $conn->real_escape_string($data['email']);
$password = $data['password'];

// Check if manager exists
$sql = "SELECT * FROM managers WHERE email = '" . $email . "' AND status = 'active'";
$result = $conn->query($sql);

if ($result->num_rows === 0) {
    sendResponse(false, 'Manager not found or inactive', null);
}

$manager = $result->fetch_assoc();

// Verify password
if (!verifyPassword($password, $manager['password'])) {
    sendResponse(false, 'Invalid password', null);
}

// Update last login
$update_sql = "UPDATE managers SET last_login = NOW(), is_online = TRUE WHERE id = " . $manager['id'];
$conn->query($update_sql);

// Set session variables
$_SESSION['manager_id'] = $manager['id'];
$_SESSION['manager_name'] = $manager['name'];
$_SESSION['manager_email'] = $manager['email'];
$_SESSION['manager_phone'] = $manager['phone'];
$_SESSION['manager_shift'] = $manager['shift_type'];
$_SESSION['last_activity'] = time();

// Create response data
$response_data = [
    'id' => $manager['id'],
    'name' => $manager['name'],
    'email' => $manager['email'],
    'phone' => $manager['phone'],
    'shift_type' => $manager['shift_type'],
    'employee_id' => $manager['employee_id']
];

sendResponse(true, 'Login successful', $response_data);
?>
