<?php
require_once 'config/database.php';
require_once 'utils/helpers.php';

try {

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

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

    // Validate required fields
    if (empty($data->email) || empty($data->password)) {
        Helpers::sendResponse(false, 'Email and password are required', null, 400);
    }

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

    // Get user by email
    $query = "SELECT u.`id`, u.`email`, u.`first_name`, u.`last_name`, u.`phone_number`, u.`gender`, 
                u.`department_id` AS department, u.`role_id`, ur.`role_name` AS role, u.`password`, u.`is_verified` 
            FROM `users` AS u JOIN user_roles AS ur ON ur.`id` = u.`role_id`
            WHERE `email` = :email";

    $stmt = $db->prepare($query);
    $stmt->bindParam(':email', $data->email);
    $stmt->execute();

    $count = (int) $stmt->rowCount();

    if (!$count) {
        Helpers::sendResponse(false, 'Invalid email or password ' . $count, null, 401);
    }

    $user = $stmt->fetch();

    // Check if user is verified
    if (!$user['is_verified']) {
        Helpers::sendResponse(false, 'Please verify your email first', null, 401);
    }

    // Check if password is set (completed registration)
    if (empty($user['password'])) {
        Helpers::sendResponse(false, 'Please complete your registration', null, 401);
    }

    // Verify password
    if (!Helpers::verifyPassword($data->password, $user['password'])) {
        Helpers::sendResponse(false, 'Invalid email or password', null, 401);
    }

    // Generate JWT token
    $token = Helpers::createJWT($user['id'], $user['email'], $user['role']);

    // Remove password hash from response
    unset($user['password']);

    Helpers::sendResponse(true, 'Login successful', [
        'token' => $token,
        'user' => $user
    ]);
} catch (PDOException $e) {
    ErrorLogger::logAuthError($e, $data->username ?? 'unknown');
    Helpers::sendResponse(false, 'An error occurred during login', null, 500);
} catch (Exception $e) {
    ErrorLogger::logAuthError($e, $data->username ?? 'unknown');
    Helpers::sendResponse(false, 'An unexpected error occurred', null, 500);
}
