<?php

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

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

$user = authenticate($pdo);

if (!isset($_GET['breakdown_id'])) {
    json_response(false, 'breakdown_id required.');
}

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

$stmt = $pdo->prepare("
    SELECT b.*, 
           f.company_name AS fleet_name,
           f.logo_path AS fleet_logo,
           s.company_name AS sp_name,
           s.logo_path AS sp_logo
    FROM breakdowns b
    JOIN companies f ON f.id = b.fleet_company_id
    LEFT JOIN companies s ON s.id = b.accepted_company_id
    WHERE b.id = ?
    LIMIT 1
");

$stmt->execute([$breakdown_id]);
$job = $stmt->fetch();

if (!$job) {
    json_response(false, 'Breakdown not found.');
}

/* Access control */
$allowed = false;

if ($user['company_id'] == $job['fleet_company_id']) $allowed = true;
if ($user['company_id'] == $job['accepted_company_id']) $allowed = true;

if (!$allowed) {
    json_response(false, 'Access denied.');
}

/* Load Photos */
$stmt = $pdo->prepare("
    SELECT file_path
    FROM breakdown_photos
    WHERE breakdown_id = ?
");
$stmt->execute([$breakdown_id]);
$photos = $stmt->fetchAll(PDO::FETCH_COLUMN);

/* Create PDF */
$pdf = new TCPDF();
$pdf->SetCreator('Assist Platform');
$pdf->SetAuthor('Assist');
$pdf->SetTitle('Job Card #' . $breakdown_id);
$pdf->AddPage();

/* Logos */
if (!empty($job['fleet_logo'])) {
    $pdf->Image(__DIR__ . '/../../' . $job['fleet_logo'], 15, 10, 40);
}

if (!empty($job['sp_logo'])) {
    $pdf->Image(__DIR__ . '/../../' . $job['sp_logo'], 150, 10, 40);
}

$pdf->Ln(30);

/* Job Info */
$html = "
<h2>Job Card #{$breakdown_id}</h2>
<hr>
<strong>Fleet Company:</strong> {$job['fleet_name']}<br>
<strong>Service Provider:</strong> {$job['sp_name']}<br>
<strong>Status:</strong> {$job['status']}<br>
<strong>Issue:</strong> {$job['issue_division']}<br>
<strong>Description:</strong> {$job['description']}<br>
<br>
<strong>Start ODO:</strong> {$job['start_odo']}<br>
<strong>End ODO:</strong> {$job['end_odo']}<br>
<strong>Travel Distance:</strong> {$job['travel_distance_km']} km<br>
<strong>Billable Distance:</strong> {$job['billable_distance_km']} km<br>
<br>
<strong>Completion Notes:</strong><br>
{$job['completion_notes']}
";

$pdf->writeHTML($html, true, false, true, false, '');

/* Signature */
if (!empty($job['signature_path'])) {
    $pdf->Ln(10);
    $pdf->Cell(0, 10, 'Customer Signature:', 0, 1);
    $pdf->Image(__DIR__ . '/../../' . $job['signature_path'], '', '', 60);
}

/* Photos */
if (!empty($photos)) {
    $pdf->AddPage();
    $pdf->Cell(0, 10, 'Job Photos', 0, 1);

    foreach ($photos as $photo) {
        $path = __DIR__ . '/../../' . $photo;
        if (file_exists($path)) {
            $pdf->AddPage();
            $pdf->Image($path, 15, 30, 180);
        }
    }
}

/* Force Download */
$pdf->Output('JobCard_Breakdown_' . $breakdown_id . '.pdf', 'D');
exit;