<?php
require("$_SERVER[DOCUMENT_ROOT]/fpdf.php");
include "$_SERVER[DOCUMENT_ROOT]/root.class.php";

$db = new db_safeguard();
$jobcard_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE record_id = {$_GET['record_id']}");
$jobcard = $jobcard_res->fetch_assoc();

function get_username($user_id)
{
    $db = new db_safeguard();
    $res = $db->query("users", "SELECT username FROM users WHERE record_id = $user_id");
    return $res->fetch_assoc()['username'];
}

function get_team($team_id)
{
    $db = new db_safeguard();
    $res = $db->query("teams", "SELECT name FROM teams WHERE record_id = $team_id");
    return $res->fetch_assoc()['name'];
}

function get_client($client_id)
{
    $db = new db_safeguard();
    $res = $db->query("clients", "SELECT `name` FROM clients WHERE record_id = $client_id");
    return $res->fetch_assoc()['name'];
}

function addSafeImage($pdf, $baseDir, $imageFile, $maxWidth = 80, $maxHeight = 80)
{
    if (empty($imageFile)) {
        $pdf->SetFont('Arial', 'I', 9);
        $pdf->SetTextColor(128, 128, 128);
        $pdf->Cell($maxWidth, 10, 'No image provided', 0, 1, 'L');
        $pdf->SetTextColor(0, 0, 0);
        return;
    }

    $imagePath = $baseDir . $imageFile;
    if (file_exists($imagePath)) {
        $pdf->Image($imagePath, $pdf->GetX(), $pdf->GetY(), $maxWidth, $maxHeight, 'PNG');
    } else {
        $pdf->SetFont('Arial', 'I', 9);
        $pdf->SetTextColor(128, 128, 128);
        $pdf->Cell($maxWidth, 10, 'Image not found: ' . basename($imagePath), 0, 1, 'L');
        $pdf->SetTextColor(0, 0, 0);
    }
}

// Create PDF with custom header and footer
class PDF extends FPDF
{
    function Header()
    {
        // Company logo or header (if available)
        // $this->Image('logo.png', 10, 6, 30);
        
        // Header line - Orange
        $this->SetDrawColor(230, 126, 34);
        $this->SetLineWidth(0.8);
        $this->Line(10, 15, 200, 15);
    }

    function Footer()
    {
        $this->SetY(-15);
        $this->SetDrawColor(230, 126, 34);
        $this->SetLineWidth(0.5);
        $this->Line(10, $this->GetY(), 200, $this->GetY());
        
        $this->SetY(-12);
        $this->SetFont('Arial', 'I', 8);
        $this->SetTextColor(128, 128, 128);
        $this->Cell(0, 10, 'Page ' . $this->PageNo() . ' of {nb}', 0, 0, 'C');
        $this->SetX(10);
        $this->Cell(0, 10, 'Generated: ' . date('Y-m-d H:i'), 0, 0, 'L');
    }

    function SectionTitle($title)
    {
        $this->SetFont('Arial', 'B', 14);
        $this->SetFillColor(230, 126, 34); // Orange
        $this->SetTextColor(255, 255, 255);
        $this->Cell(0, 10, $title, 0, 1, 'L', true);
        $this->SetTextColor(0, 0, 0);
        $this->Ln(3);
    }

    function InfoRow($label, $value, $fullWidth = false)
    {
        $this->SetFont('Arial', 'B', 10);
        $this->SetTextColor(41, 128, 185); // Blue for labels
        
        if ($fullWidth) {
            $this->Cell(0, 7, $label . ':', 0, 1, 'L');
            $this->SetFont('Arial', '', 10);
            $this->SetTextColor(0, 0, 0);
            $this->MultiCell(0, 6, $value ?: 'N/A', 0, 'L');
        } else {
            $this->Cell(55, 7, $label . ':', 0, 0, 'L');
            $this->SetFont('Arial', '', 10);
            $this->SetTextColor(0, 0, 0);
            $this->Cell(0, 7, $value ?: 'N/A', 0, 1, 'L');
        }
        $this->SetTextColor(0, 0, 0);
    }

    function TableHeader($headers, $widths)
    {
        $this->SetFont('Arial', 'B', 10);
        $this->SetFillColor(52, 152, 219); // Blue for table headers
        $this->SetTextColor(255, 255, 255);
        $this->SetDrawColor(41, 128, 185); // Blue border
        $this->SetLineWidth(0.3);
        
        foreach ($headers as $i => $header) {
            $this->Cell($widths[$i], 8, $header, 1, 0, 'C', true);
        }
        $this->Ln();
        $this->SetTextColor(0, 0, 0);
    }

    function TableRow($data, $widths, $fill = false)
    {
        $this->SetFont('Arial', '', 9);
        $fillColor = $fill ? array(236, 240, 241) : array(255, 255, 255);
        $this->SetFillColor($fillColor[0], $fillColor[1], $fillColor[2]);
        $this->SetDrawColor(189, 195, 199);
        
        foreach ($data as $i => $cell) {
            $this->Cell($widths[$i], 7, $cell, 1, 0, 'L', true);
        }
        $this->Ln();
    }
}

$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage('P');

// MAIN HEADER
$pdf->Ln(5);
$pdf->SetFont('Arial', 'B', 24);
$pdf->SetTextColor(230, 126, 34); // Orange for main title
$pdf->Cell(0, 12, "JOB CARD", 0, 1, 'C');
$pdf->SetFont('Arial', 'B', 16);
$pdf->SetTextColor(41, 128, 185); // Blue for subtitle
$pdf->Cell(0, 8, "JC No: " . $jobcard['jc_no'], 0, 1, 'C');
$pdf->SetTextColor(0, 0, 0);
$pdf->Ln(5);

// JOB INFORMATION SECTION
$pdf->SectionTitle('Job Information');
$pdf->InfoRow('Date Created', $jobcard['date_created']);
$pdf->InfoRow('Action Date', $jobcard['action_date']);
$pdf->InfoRow('User Created', get_username($jobcard['user_id']));
$pdf->InfoRow('Team Assigned', get_team($jobcard['team_assigned_id']));
$pdf->Ln(3);

// CLIENT INFORMATION SECTION
$pdf->SectionTitle('Client Information');
$pdf->InfoRow('Client ID', $jobcard['client_id']);
$pdf->InfoRow('Address', $jobcard['address'], true);
$pdf->InfoRow('Contact Name', $jobcard['contact_name']);
$pdf->InfoRow('Contact Number', $jobcard['contact_number']);
$pdf->InfoRow('Other Number', $jobcard['other_number']);
$pdf->InfoRow('Alternate Number', $jobcard['alternate_number']);
$pdf->InfoRow('Drill Coordinates', $jobcard['drill_co_ordinates']);
$pdf->Ln(3);

// OPERATION DETAILS SECTION
$pdf->SectionTitle('Operation Details');
$pdf->InfoRow('Diesel Start', $jobcard['diesel_start']);
$pdf->InfoRow('Diesel Stop', $jobcard['diesel_stop']);
$pdf->InfoRow('Water Flow', $jobcard['water_flow']);
$pdf->InfoRow('Water Strike', $jobcard['water_strike']);
$pdf->InfoRow('Compressor Hours', $jobcard['compressor_hours']);
$pdf->InfoRow('Interested In Pump', $jobcard['interested_in_pump']);

// PAGE 2 - SUMMARY
$pdf->AddPage('P');
$pdf->Ln(5);
$pdf->SectionTitle('Job Card Summary');

// Calculate summary data
$job_card_res = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$_GET['record_id']} AND type != 'DEPARTURE' AND type != 'ARRIVED' ORDER BY record_id ASC");

$drilling_meters = $riem_meters = $casing_meters = $blasting_meters = 0;
$total_riem_time = $total_drilling_time = $total_casing_time = $total_blasting_time = 0;

while ($job_card = $job_card_res->fetch_assoc()) {
    switch ($job_card['type']) {
        case 'RIEM_START':
            $riem_start = $job_card['date_time'];
            break;
        case 'RIEMING_START':
            $riem_start = $job_card['date_time'];
            break;
        case 'RIEMING_RESUME':
            if (isset($riem_start)) {
                $riem_meters += $job_card['meters'];
            }
            break;
        case 'RIEMING_PAUSED':
            if (isset($riem_start)) {
                $riem_meters += $job_card['meters'];
            }
            break;
        case 'RIEMING_STOP':
            if (isset($riem_start)) {
                $riem_stop = $job_card['date_time'];
                $riem_meters += $job_card['meters'];
                $total_riem_time += strtotime($riem_stop) - strtotime($riem_start);
            }
            break;


        case 'DRILLING_START':
            $drilling_start = $job_card['date_time'];
            break;
        case 'DRILLING_RESUME':
            if (isset($drilling_start)) {
                $drilling_meters += $job_card['meters'];
            }
            break;
        case 'DRILLING_PAUSE':
            if (isset($drilling_start)) {
                $drilling_meters += $job_card['meters'];
            }
            break;
        case 'DRILLING_STOP':
            if (isset($drilling_start)) {
                $drilling_stop = $job_card['date_time'];
                $drilling_meters += $job_card['meters'];
                $total_drilling_time += strtotime($drilling_stop) - strtotime($drilling_start);
            }
            break;


        case 'CASING_START':
            $casing_start = $job_card['date_time'];
            break;
        case 'CASING_RESUME':
            if (isset($casing_start)) {
                $casing_meters += $job_card['meters'];
            }
            break;
        case 'CASING_PAUSE':
            if (isset($casing_start)) {
                $casing_meters += $job_card['meters'];
            }
            break;
        case 'CASING_STOP':
            if (isset($casing_start)) {
                $casing_stop = $job_card['date_time'];
                $casing_meters += $job_card['meters'];
                $total_casing_time += strtotime($casing_stop) - strtotime($casing_start);
            }
            break;


        case 'BLASTING_START':
            $blasting_start = $job_card['date_time'];
            break;
        case 'BLASTING_RESUME':
            if (isset($blasting_start)) {
                $blasting_meters += $job_card['meters'];
            }
            break;
        case 'BLASTING_PAUSE':
            if (isset($blasting_start)) {
                $blasting_meters += $job_card['meters'];
            }
            break;
        case 'BLASTING_STOP':
            if (isset($blasting_start)) {
                $blasting_stop = $job_card['date_time'];
                $blasting_meters += $job_card['meters'];
                $total_blasting_time += strtotime($blasting_stop) - strtotime($blasting_start);
            }
            break;
    }
}

$total_work_time = $total_riem_time + $total_drilling_time + $total_casing_time + $total_blasting_time;
$total_meters = $riem_meters + $drilling_meters + $casing_meters + $blasting_meters;

// Summary table
$headers = array('Description', 'Total Meters', 'Total Time');
$widths = array(80, 55, 55);

$pdf->TableHeader($headers, $widths);

$data = array(
    array('RIEM', $riem_meters, gmdate('H:i', $total_riem_time)),
    array('DRILLING', $drilling_meters, gmdate('H:i', $total_drilling_time)),
    array('CASING', $casing_meters, gmdate('H:i', $total_casing_time)),
    array('BLASTING', $blasting_meters, gmdate('H:i', $total_blasting_time))
);

$fill = false;
foreach ($data as $row) {
    $pdf->TableRow($row, $widths, $fill);
    $fill = !$fill;
}

// Totals row - Orange for emphasis
$pdf->SetFont('Arial', 'B', 10);
$pdf->SetFillColor(230, 126, 34); // Orange
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell($widths[0], 8, 'TOTALS', 1, 0, 'L', true);
$pdf->Cell($widths[1], 8, $total_meters, 1, 0, 'L', true);
$pdf->Cell($widths[2], 8, gmdate('H:i', $total_work_time), 1, 1, 'L', true);
$pdf->SetTextColor(0, 0, 0);

// PAGE 3 - TIMELINE
$pdf->AddPage('P');
$pdf->Ln(5);
$pdf->SectionTitle('Job Card Timeline');

$headers = array('Description', 'Meters', 'Date & Time');
$widths = array(70, 40, 80);

$pdf->TableHeader($headers, $widths);

$job_card_time_res = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$_GET['record_id']} AND type != 'DEPARTURE' AND type != 'ARRIVED' ORDER BY record_id ASC");

$fill = false;
while ($job_card = $job_card_time_res->fetch_assoc()) {
    $data = array(
        $job_card['type'],
        $job_card['meters'],
        $job_card['date_time']
    );
    $pdf->TableRow($data, $widths, $fill);
    $fill = !$fill;
}

// PAGE 4 - PAYMENTS
$pdf->AddPage('P');
$pdf->Ln(5);
$pdf->SectionTitle('Payment Records');

$payments_res = $db->query("jobcard_payments", "SELECT * FROM jobcard_payments WHERE jobcard_id = {$_GET['record_id']} ORDER BY date_time ASC");

if ($payments_res->num_rows == 0) {
    $pdf->SetFont('Arial', 'I', 11);
    $pdf->SetTextColor(128, 128, 128);
    $pdf->Cell(0, 10, 'No payment records available for this job card.', 0, 1, 'C');
} else {
    $headers = array('Payment Method', 'User', 'Amount', 'Date & Time', 'File');
    $widths = array(35, 35, 35, 50, 35);
    
    $pdf->TableHeader($headers, $widths);
    
    $fill = false;
    while ($payment = $payments_res->fetch_assoc()) {
        $user = get_username($payment['user_id']);
        $amount = 'R ' . number_format($payment['amount'], 2);
        $file_display = !empty($payment['file']) ? 'Yes' : 'No';
        
        $data = array(
            strtoupper($payment['payment_method']),
            $user,
            $amount,
            $payment['date_time'],
            $file_display
        );
        $pdf->TableRow($data, $widths, $fill);
        $fill = !$fill;
    }
    
    // Calculate total
    $payments_res = $db->query("jobcard_payments", "SELECT SUM(amount) as total FROM jobcard_payments WHERE jobcard_id = {$_GET['record_id']}");
    $total_payment = $payments_res->fetch_assoc()['total'];
    
    $pdf->Ln(3);
    $pdf->SetFont('Arial', 'B', 11);
    $pdf->SetTextColor(230, 126, 34);
    $pdf->Cell(70, 8, 'TOTAL PAYMENTS:', 0, 0, 'R');
    $pdf->SetTextColor(0, 0, 0);
    $pdf->Cell(0, 8, 'R ' . number_format($total_payment, 2), 0, 1, 'L');
}

// NOTES SECTION - WITH PAGINATION (5 NOTES PER PAGE)
$pdf->AddPage('P');
$pdf->Ln(5);
$pdf->SectionTitle('Notes & Observations');

$i = 1;
$notes_per_page = 5;
$notes_on_current_page = 0;

$notes_res = $db->query("notes", "SELECT * FROM notes WHERE jobcard_id = {$_GET['record_id']} ORDER BY record_id ASC");

if ($notes_res->num_rows == 0) {
    $pdf->SetFont('Arial', 'I', 11);
    $pdf->SetTextColor(128, 128, 128);
    $pdf->Cell(0, 10, 'No notes available for this job card.', 0, 1, 'C');
    $pdf->SetTextColor(0, 0, 0);
} else {
    while ($notes = $notes_res->fetch_assoc()) {
        // Check if we need a new page (after 5 notes)
        if ($notes_on_current_page >= $notes_per_page) {
            $pdf->AddPage('P');
            $pdf->Ln(5);
            $pdf->SectionTitle('Notes & Observations (Continued)');
            $notes_on_current_page = 0;
        }
        
        // Note box with border
        $pdf->SetDrawColor(189, 195, 199);
        $pdf->SetLineWidth(0.5);
        $pdf->Rect($pdf->GetX(), $pdf->GetY(), 190, 5, 'D');
        
        $pdf->SetFillColor(236, 240, 241);
        $pdf->SetFont('Arial', 'B', 11);
        $pdf->Cell(190, 5, 'Note #' . $i, 0, 1, 'L', true);
        
        $pdf->SetFont('Arial', 'B', 9);
        $pdf->SetTextColor(41, 128, 185); // Blue for note labels
        $pdf->Cell(40, 6, 'Description:', 0, 0, 'L');
        $pdf->SetFont('Arial', '', 9);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->Cell(0, 6, $notes['reason'], 0, 1, 'L');
        
        $pdf->SetFont('Arial', 'B', 9);
        $pdf->SetTextColor(41, 128, 185); // Blue for note labels
        $pdf->Cell(40, 6, 'Date & Time:', 0, 0, 'L');
        $pdf->SetFont('Arial', '', 9);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->Cell(0, 6, $notes['date_time'], 0, 1, 'L');
        
        if (!empty($notes['note'])) {
            $pdf->SetFont('Arial', 'B', 9);
            $pdf->SetTextColor(41, 128, 185); // Blue for note labels
            $pdf->Cell(40, 6, 'Additional Notes:', 0, 1, 'L');
            $pdf->SetFont('Arial', '', 9);
            $pdf->SetTextColor(0, 0, 0);
            $pdf->MultiCell(0, 5, $notes['note'], 0, 'L');
        }
        
        $pdf->Ln(2);
        
        // Add image if available
        if ($notes['reason'] == "CURRENT BIT") {
            addSafeImage($pdf, "../jobcards/drilling_bit/", $notes['image'], 80, 60);
        } else {
            addSafeImage($pdf, "../jobcards/notes/", $notes['image'], 80, 60);
        }
        
        $pdf->Ln(5);
        $i++;
        $notes_on_current_page++;
    }
}

$pdf->Output("I");