<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireAuth();
$db = getDB();
$jobCardId = (int) post('job_card_id', 0);
$eventType = post('event_type', '');
$odoReading = post('odo_reading') !== null && post('odo_reading') !== '' ? (int) post('odo_reading') : null;

if (!$jobCardId)
    apiError('Job card ID required.', 422);
require_once __DIR__ . '/../fleet/odo_helper.php';

$allowed = [
    'depart',
    'arrive_site',
    'start_work',
    'depart_site',
    'arrive_base',
    'pause_travel',
    'resume_travel',
    'pause_work',
    'resume_work',
    'completed',
    'internal_complete',
    'invoiced',
    'no_charge',
    'cancelled'
];
if (!in_array($eventType, $allowed))
    apiError('Invalid event type.', 422);

// Events that require an ODO reading
$requiresOdo = ['depart', 'arrive_site', 'depart_site', 'arrive_base', 'pause_travel', 'resume_travel'];
if (in_array($eventType, $requiresOdo) && $odoReading === null) {
    apiError('ODO reading is required for this event.', 422);
}

// Validate ODO is not lower than the latest recorded reading
if ($odoReading !== null) {
    $vehRow = $db->prepare("SELECT vehicle_id FROM job_cards WHERE id=?");
    $vehRow->execute([$jobCardId]);
    $vehData = $vehRow->fetch();
    if ($vehData && $vehData['vehicle_id']) {
        validateOdo($db, $vehData['vehicle_id'], $odoReading);
    }
}

// Log the event
$db->prepare("
    INSERT INTO job_card_time_logs (job_card_id, user_id, event_type, event_time, odo_reading, lat, lng, notes)
    VALUES (?, ?, ?, NOW(), ?, ?, ?, ?)
")->execute([$jobCardId, $user['id'], $eventType, $odoReading, post('lat'), post('lng'), post('notes')]);

// Update job_cards ODO fields based on event
$jcRow = $db->prepare("SELECT odo_start, odo_end, status FROM job_cards WHERE id=?");
$jcRow->execute([$jobCardId]);
$jc = $jcRow->fetch();

if ($odoReading !== null) {
    if ($eventType === 'depart' && !$jc['odo_start']) {
        // First departure — set odo_start
        $db->prepare("UPDATE job_cards SET odo_start=? WHERE id=?")->execute([$odoReading, $jobCardId]);
    } elseif ($eventType === 'arrive_base') {
        // Arrived back at base — set odo_end
        $db->prepare("UPDATE job_cards SET odo_end=? WHERE id=?")->execute([$odoReading, $jobCardId]);
    }
    // Also update fleet ODO via odo_helper
    $vehicleRow = $db->prepare("SELECT vehicle_id FROM job_cards WHERE id=?");
    $vehicleRow->execute([$jobCardId]);
    $vehicle = $vehicleRow->fetch();
    if ($vehicle && $vehicle['vehicle_id']) {
        $db->prepare("UPDATE fleet_vehicles SET current_odo=GREATEST(COALESCE(current_odo,0),?) WHERE id=?")
            ->execute([$odoReading, $vehicle['vehicle_id']]);
    }
}

// Status map — pauses stay in same status (just log the event)
$statusMap = [
    'depart' => 'travelling',
    'arrive_site' => 'on_site',
    'start_work' => 'working',
    'depart_site' => 'travelling',
    'arrive_base' => 'working',
    'completed' => 'completed',
    'internal_complete' => 'internal_complete',
    'invoiced' => 'invoiced',
    'no_charge' => 'no_charge',
    'cancelled' => 'cancelled',
    // pauses do not change status
];

if (isset($statusMap[$eventType])) {
    $completedAt = in_array($eventType, ['completed', 'internal_complete', 'no_charge']) ? ', completed_at=NOW()' : '';
    $db->prepare("UPDATE job_cards SET status=?{$completedAt} WHERE id=?")->execute([$statusMap[$eventType], $jobCardId]);
}

// ── Email notifications for terminal status events ────────
$emailStatuses = ['completed', 'internal_complete', 'invoiced', 'no_charge'];
if (in_array($eventType, $emailStatuses) && $jc['status'] !== $statusMap[$eventType]) {
    try {
        require_once __DIR__ . '/../config/mailer.php';
        require_once __DIR__ . '/../emails/templates.php';
        require_once __DIR__ . '/_pdf_generator.php';

        $cfg        = getMailerConfig($db);
        $appUrl     = $cfg['email_app_url'] ?? '';
        $adminEmail = getAdminEmail($db);

        // Company name for client emails
        $companyStmt = $db->query("SELECT setting_value FROM settings WHERE setting_key='company_name' LIMIT 1");
        $companyName = $companyStmt ? ($companyStmt->fetchColumn() ?: 'Elegant Work') : 'Elegant Work';

        // Fetch full job card with client + tech
        $fullJc = $db->prepare("
            SELECT jc.*, c.company_name AS client_name,
                   u.full_name AS assigned_name, u.email AS assigned_email
            FROM job_cards jc
            LEFT JOIN clients c ON c.id = jc.client_id
            LEFT JOIN users u ON u.id = jc.assigned_to
            WHERE jc.id = ?
        ");
        $fullJc->execute([$jobCardId]);
        $jcFull = $fullJc->fetch();
        if (!$jcFull) throw new Exception('JC not found');
        $jcFull['_app_url'] = rtrim($appUrl, '/');

        // Primary contact email from client_contacts
        $jcFull['client_email']        = null;
        $jcFull['client_contact_name'] = $jcFull['client_name'];
        if ($jcFull['client_id']) {
            $cc = $db->prepare("SELECT email, full_name FROM client_contacts WHERE client_id=? AND is_primary=1 LIMIT 1");
            $cc->execute([$jcFull['client_id']]);
            $ccRow = $cc->fetch();
            if ($ccRow) {
                $jcFull['client_email']        = $ccRow['email'];
                $jcFull['client_contact_name'] = $ccRow['full_name'];
            }
        }

        $techEmail     = $jcFull['assigned_email'] ?? null;
        $techName      = $jcFull['assigned_name']  ?? null;
        $clientEmail   = $jcFull['client_email']   ?? null;
        $clientName    = $jcFull['client_contact_name'] ?? $jcFull['client_name'] ?? null;
        $isInternal    = (bool)($jcFull['is_internal'] ?? false);

        // ── job_completed — internal: admin + tech, client: tailored ──
        if (in_array($eventType, ['completed', 'internal_complete'])) {
            $rule = getNotifRule($db, 'job_completed');
            if ($rule && $rule['is_enabled']) {
                // Internal subject
                $intSubject = "✅ Job Completed: {$jcFull['job_number']}";
                if ($rule['notify_admin'] && $adminEmail) {
                    $html = tplJobCompleted($jcFull, 'Admin', false, $appUrl);
                    queueEmail($db, 'job_completed', $adminEmail, 'Admin', $intSubject, $html, 'job_card', $jobCardId);
                }
                if ($rule['notify_assigned_tech'] && $techEmail && $techEmail !== $adminEmail) {
                    $html = tplJobCompleted($jcFull, $techName, false, $appUrl);
                    queueEmail($db, 'job_completed', $techEmail, $techName, $intSubject, $html, 'job_card', $jobCardId);
                }
                // Client — friendly customer email
                if ($rule['notify_client'] && $clientEmail && !$isInternal) {
                    $clientSubject = "Work Completed at Your Site — {$jcFull['title']}";
                    $jcFull['_pdf_url'] = generatePdfAccessToken($db, $jobCardId, 'client', $appUrl);
                    $html = tplClientJobCompleted($jcFull, $clientName, $companyName);
                    queueEmail($db, 'job_completed', $clientEmail, $clientName, $clientSubject, $html, 'job_card', $jobCardId);
                }
            }
        }

        // ── job_invoiced / no_charge — internal + client with PDF ──
        if (in_array($eventType, ['invoiced', 'no_charge'])) {
            $rule = getNotifRule($db, 'job_invoiced');
            if ($rule && $rule['is_enabled']) {
                $isNoCharge  = $eventType === 'no_charge';
                $pdfFileName = $jcFull['job_number'] . '_job_record.pdf';

                // Generate PDFs
                $clientPdfPath   = generateJobCardPdf($db, $jobCardId, 'client');
                $internalPdfPath = generateJobCardPdf($db, $jobCardId, 'internal');

                // Internal notifications
                $intSubject = $isNoCharge
                    ? "🆓 No Charge: {$jcFull['job_number']}"
                    : "🧾 Invoiced: {$jcFull['job_number']}";

                if ($rule['notify_admin'] && $adminEmail) {
                    $html = tplJobInvoiced($jcFull, 'Admin', false, $appUrl);
                    queueEmail($db, 'job_invoiced', $adminEmail, 'Admin', $intSubject, $html, 'job_card', $jobCardId,
                        $internalPdfPath, $pdfFileName);
                }
                if ($rule['notify_assigned_tech'] && $techEmail && $techEmail !== $adminEmail) {
                    $html = tplJobInvoiced($jcFull, $techName, false, $appUrl);
                    queueEmail($db, 'job_invoiced', $techEmail, $techName, $intSubject, $html, 'job_card', $jobCardId,
                        $internalPdfPath, $pdfFileName);
                }

                // Client — tailored friendly email with client PDF attached
                if ($rule['notify_client'] && $clientEmail && !$isInternal) {
                    $jcFull['_pdf_url'] = generatePdfAccessToken($db, $jobCardId, 'client', $appUrl);
                    $clientSubject = "Job Card Document for {$jcFull['job_number']} — {$jcFull['title']}";
                    $html = $isNoCharge
                        ? tplClientNoCharge($jcFull, $clientName, $companyName)
                        : tplClientInvoice($jcFull, $clientName, $companyName);
                    queueEmail($db, 'job_invoiced', $clientEmail, $clientName, $clientSubject, $html, 'job_card', $jobCardId,
                        $clientPdfPath, $pdfFileName);
                } else {
                    // No client to email — discard client PDF
                    if ($clientPdfPath) @unlink($clientPdfPath);
                }
            }
        }

    } catch (Exception $emailErr) {
        error_log('[EWG Email] log_time trigger failed: ' . $emailErr->getMessage());
    }
}

apiSuccess(['odo_reading' => $odoReading], 'Event logged.');