<?php

require_once __DIR__ . '/../../core/bootstrap.php';

/* ----------------------------------------------------------
   METHOD CHECK
---------------------------------------------------------- */

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.', [], 405);
}

/* ----------------------------------------------------------
   AUTHENTICATION
---------------------------------------------------------- */

$user = authenticate($pdo);

if (!in_array($user['role'], ['sp_admin', 'artisan'], true)) {
    json_response(false, 'Access denied. SP role required.', [], 403);
}

$sp_company_id = (int)$user['company_id'];
$rsp_id        = (int)$user['rsp_id'];

if ($sp_company_id <= 0) {
    json_response(false, 'Service provider not linked to company.', [], 403);
}

/* ----------------------------------------------------------
   INPUT VALIDATION
---------------------------------------------------------- */

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

if (!is_array($input) || empty($input['breakdown_id'])) {
    json_response(false, 'Breakdown ID required.', [], 400);
}

$breakdown_id = (int)$input['breakdown_id'];

if ($breakdown_id <= 0) {
    json_response(false, 'Invalid breakdown ID.', [], 400);
}

/* ----------------------------------------------------------
   TRANSACTION
---------------------------------------------------------- */

$pdo->beginTransaction();

try {

    /*
    |----------------------------------------------------------
    | Validate Breakdown + Tenant Boundary
    |----------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        SELECT
            b.id,
            b.status,
            b.accepted_company_id,
            b.broadcast_expires_at,
            b.archived_at,
            f.rsp_id
        FROM breakdowns b
        JOIN companies f ON f.id = b.fleet_company_id
        WHERE b.id = ?
        LIMIT 1
    ");

    $stmt->execute([$breakdown_id]);
    $breakdown = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$breakdown) {
        $pdo->rollBack();
        json_response(false, 'Breakdown not found.', [], 404);
    }

    /* Tenant isolation */

    if ((int)$breakdown['rsp_id'] !== $rsp_id) {
        $pdo->rollBack();
        json_response(false, 'Access denied.', [], 403);
    }

    /* Archive protection */

    if (!empty($breakdown['archived_at'])) {
        $pdo->rollBack();
        json_response(false, 'Archived jobs cannot be accepted.', [], 403);
    }

    /* Broadcast expiry protection */

    if (!empty($breakdown['broadcast_expires_at'])) {

        if (strtotime($breakdown['broadcast_expires_at']) < time()) {
            $pdo->rollBack();
            json_response(false, 'Broadcast has expired.', [], 409);
        }
    }

    /* Must be broadcasting and unassigned */

    if (
        $breakdown['status'] !== 'broadcasting' ||
        $breakdown['accepted_company_id'] !== null
    ) {
        $pdo->rollBack();
        json_response(false, 'Job already accepted or unavailable.', [], 409);
    }

    /*
    |----------------------------------------------------------
    | ATOMIC ACCEPT
    |----------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        UPDATE breakdowns
        SET
            accepted_company_id = ?,
            allocated_at = NOW(),
            status = 'allocated'
        WHERE id = ?
          AND status = 'broadcasting'
          AND accepted_company_id IS NULL
    ");

    $stmt->execute([
        $sp_company_id,
        $breakdown_id
    ]);

    if ($stmt->rowCount() === 0) {

        $pdo->rollBack();

        json_response(false, 'Job already accepted by another provider.', [], 409);
    }

    $pdo->commit();

    json_response(true, 'Job successfully accepted.', [
        'breakdown_id' => $breakdown_id,
        'status'       => 'allocated'
    ]);

} catch (Throwable $e) {

    $pdo->rollBack();

    json_response(false, 'Failed to accept job.', [], 500);
}