<?php
declare(strict_types=1);

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/response.php';
require_once __DIR__ . '/../system/audit.php';

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

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

/* =========================
   METHOD
   ========================= */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    error_bad_request('Method not allowed');
}

/* =========================
   INPUT
   ========================= */
$payload = json_decode(file_get_contents('php://input'), true);

if (!is_array($payload)) {
    error_bad_request('Invalid JSON body');
}

$email    = trim(strtolower($payload['email'] ?? ''));
$password = (string)($payload['password'] ?? '');

if ($email === '' || $password === '') {
    error_bad_request('Email and password required');
}

/* =========================
   FETCH USER + COMPANY + PRODUCT
   ========================= */
$stmt = $pdo->prepare("
    SELECT
        u.id,
        u.email,
        u.password_hash,
        u.role_key,
        u.status,
        u.email_verified,
        u.company_id,
        c.rsp_id,
        c.product_id
    FROM users u
    INNER JOIN companies c ON c.id = u.company_id
    WHERE u.email = :email
      AND u.deleted_at IS NULL
    LIMIT 1
");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || !password_verify($password, $user['password_hash'])) {
    error_unauthorized('Invalid credentials');
}

/* =========================
   LIFECYCLE ENFORCEMENT
   ========================= */
$status = strtolower(trim((string)$user['status']));

if ((int)$user['email_verified'] !== 1 || $status !== 'active') {
    error_forbidden('Account not active');
}

/* =========================
   PRODUCT ENFORCEMENT
   ========================= */

/*
Mining bootstrap should define:
define('PRODUCT_ID', 1);

Assist bootstrap should define:
define('PRODUCT_ID', 2);
*/

if (defined('PRODUCT_ID')) {
    if ((int)$user['product_id'] !== PRODUCT_ID) {
        error_forbidden('Invalid platform access');
    }
}

/* =========================
   SESSION AUTH
   ========================= */
$_SESSION['user_id']     = (int)$user['id'];
$_SESSION['role_key']    = $user['role_key'];
$_SESSION['company_id']  = (int)$user['company_id'];
$_SESSION['rsp_id']      = (int)$user['rsp_id'];
$_SESSION['product_id']  = (int)$user['product_id'];
$_SESSION['email']       = $user['email'];
$_SESSION['login_time']  = time();
$_SESSION['is_global']   = in_array($user['role_key'], ['super_admin','support'], true);

/* =========================
   PLATFORM ACCESS
   ========================= */
require_once __DIR__ . '/../system/platform_access.php';

if (!platform_enabled($pdo, (int)$user['id'], 'mobile')) {
    error_forbidden('Mobile access disabled for this user');
}

/* =========================
   TOKEN GENERATION
   ========================= */
$token = bin2hex(random_bytes(32));

$stmt = $pdo->prepare("
    INSERT INTO api_tokens (
        token,
        user_id,
        created_at,
        expires_at,
        revoked_at
    ) VALUES (
        :token,
        :user_id,
        NOW(),
        DATE_ADD(NOW(), INTERVAL 24 HOUR),
        NULL
    )
");

$stmt->execute([
    'token'   => $token,
    'user_id' => (int)$user['id']
]);

/* =========================
   RESPONSE
   ========================= */
success('Login successful', [
    'token' => $token,
    'user' => [
        'id'         => (int)$user['id'],
        'email'      => $user['email'],
        'role_key'   => $user['role_key'],
        'company_id' => (int)$user['company_id'],
        'product_id' => (int)$user['product_id']
    ]
]);

audit_log(
    $pdo,
    $user,
    'login',
    'auth',
    null,
    ['session_id' => session_id()]
);
