<?php
// POST /api/jobcards/costing.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user = requireAuth();
$db = getDB();
$jobCardId = (int) post('job_card_id', 0);
if (!$jobCardId)
    apiError('Job card ID required.', 422);

require_once __DIR__ . '/_costing_engine.php';

try {
    // ── Settings ────────────────────────────────────────────
    $defaultDays = 21.67;
    $defaultHours = 8;
    try {
        $sStmt = $db->query("SELECT setting_key, setting_value FROM settings WHERE setting_group IN ('hr','finance')");
        foreach ($sStmt->fetchAll() as $s) {
            if ($s['setting_key'] === 'working_days_per_month')
                $defaultDays = (float) $s['setting_value'];
            if ($s['setting_key'] === 'working_hours_per_day')
                $defaultHours = (float) $s['setting_value'];
        }
    } catch (Exception $ignored) { /* settings table may not exist yet */
    }

    // ── Job card ────────────────────────────────────────────
    $jcStmt = $db->prepare("
        SELECT jc.*, c.company_name AS client_name,
               v.registration AS vehicle_reg, v.quote_rate_per_km, v.cost_per_km,
               v.make AS vehicle_make, v.model AS vehicle_model
        FROM job_cards jc
        LEFT JOIN clients c ON c.id = jc.client_id
        LEFT JOIN fleet_vehicles v ON v.id = jc.vehicle_id
        WHERE jc.id=?
    ");
    $jcStmt->execute([$jobCardId]);
    $card = $jcStmt->fetch();
    if (!$card)
        apiError('Job card not found.', 404);

    // ── Time logs — ALL logs merged for single shared timeline ──
    $logsStmt = $db->prepare("
        SELECT tl.*, u.full_name, u.id AS uid
        FROM job_card_time_logs tl
        JOIN users u ON u.id = tl.user_id
        WHERE tl.job_card_id=?
        ORDER BY tl.event_time ASC
    ");
    $logsStmt->execute([$jobCardId]);
    $timeLogs = $logsStmt->fetchAll();

    // ── Assigned team members (lead + extras from job_card_technicians) ──
    // Use UNION so the lead technician (assigned_to) is always included,
    // even if they are not duplicated in job_card_technicians.
    $teamStmt = $db->prepare("
        SELECT u.id AS user_id, u.full_name
        FROM users u
        WHERE u.id = (SELECT assigned_to FROM job_cards WHERE id = ?)
          AND u.id IS NOT NULL
        UNION
        SELECT jct.user_id, u2.full_name
        FROM job_card_technicians jct
        JOIN users u2 ON u2.id = jct.user_id
        WHERE jct.job_card_id = ?
    ");
    $teamStmt->execute([$jobCardId, $jobCardId]);
    $teamMembers = $teamStmt->fetchAll();

    // Fallback: if no team members recorded, use unique users from time logs
    if (empty($teamMembers)) {
        $seen = [];
        foreach ($timeLogs as $l) {
            if (!isset($seen[$l['uid']])) {
                $seen[$l['uid']] = true;
                $teamMembers[] = ['user_id' => $l['uid'], 'full_name' => $l['full_name']];
            }
        }
    }

    // ── Hourly rates for each team member ────────────────────
    $techRates = [];
    foreach ($teamMembers as $tm) {
        $tid = $tm['user_id'];
        $rStmt = $db->prepare("
            SELECT es.basic_salary, es.salary_type, u.full_name,
                   COALESCE(e.days_per_month, ?) AS days_pm,
                   COALESCE(e.hours_per_day, ?)  AS hours_pd
            FROM users u
            LEFT JOIN employees e ON e.user_id = u.id
            LEFT JOIN employee_salaries es ON es.employee_id = e.id
            WHERE u.id=?
            ORDER BY es.effective_date DESC LIMIT 1
        ");
        $rStmt->execute([$defaultDays, $defaultHours, $tid]);
        $r = $rStmt->fetch();
        $hourlyRate = 0;
        $dpm = $defaultDays;
        $hpd = $defaultHours;
        if ($r) {
            $dpm = (float) ($r['days_pm'] ?: $defaultDays);
            $hpd = (float) ($r['hours_pd'] ?: $defaultHours);
            if ($r['salary_type'] === 'hourly') {
                $hourlyRate = (float) $r['basic_salary'];
            } elseif ($r['salary_type'] === 'monthly') {
                $mh = $dpm * $hpd;
                $hourlyRate = $mh > 0 ? round((float) $r['basic_salary'] / $mh, 2) : 0;
            } elseif ($r['salary_type'] === 'daily') {
                $hourlyRate = $hpd > 0 ? round((float) $r['basic_salary'] / $hpd, 2) : 0;
            }
        }
        $techRates[$tid] = [
            'rate' => $hourlyRate,
            'name' => $r['full_name'] ?? $tm['full_name'],
            'dpm' => $dpm,
            'hpd' => $hpd,
        ];
    }

    // ── Single shared timeline — all team members worked simultaneously ──
    $segs = calcSegments($timeLogs); // use ALL logs merged for the shared timeline

    $drivingMin = $segs['driving_min'];
    $workingMin = $segs['working_min'];
    $pausedTravelMin = $segs['paused_travel_min'];
    $pausedWorkMin = $segs['paused_work_min'];
    $totalPausedMin = $pausedTravelMin + $pausedWorkMin;
    $totalMin = $drivingMin + $workingMin; // paused NOT included in cost

    // Apply the same shared time to every team member's rate
    $techHours = [];
    foreach ($techRates as $tid => $tr) {
        $rate = $tr['rate'];
        $techHours[$tid] = [
            'name' => $tr['name'],
            'hourly_rate' => $rate,
            'days_per_month' => $tr['dpm'],
            'hours_per_day' => $tr['hpd'],
            'driving_minutes' => round($drivingMin),
            'working_minutes' => round($workingMin),
            'paused_travel_min' => round($pausedTravelMin),
            'paused_work_min' => round($pausedWorkMin),
            'total_paused_minutes' => round($totalPausedMin),
            'total_minutes' => round($totalMin),
            'driving_hours' => round($drivingMin / 60, 2),
            'working_hours' => round($workingMin / 60, 2),
            'paused_hours' => round($totalPausedMin / 60, 2),
            'total_hours' => round($totalMin / 60, 2),
            'labour_cost' => round(($totalMin / 60) * $rate, 2),
        ];
    }
    $totalLabourCost = array_sum(array_column($techHours, 'labour_cost'));

    // ── Travel ───────────────────────────────────────────────
    $odoStart = (int) $card['odo_start'];
    $odoEnd = (int) $card['odo_end'];
    $kmTravelled = ($odoStart && $odoEnd) ? max(0, $odoEnd - $odoStart) : 0;
    $costPerKm = (float) ($card['cost_per_km'] ?? 0);
    $quotePerKm = (float) ($card['quote_rate_per_km'] ?? 0);
    $travelCost = $kmTravelled * $costPerKm;
    $travelQuote = $kmTravelled * $quotePerKm;

    // ── Consumables ──────────────────────────────────────────
    $stStmt = $db->prepare("
        SELECT st.*, si.name AS item_name, si.unit, si.sku
        FROM stock_transactions st
        JOIN stock_items si ON si.id = st.stock_item_id
        WHERE st.job_card_id=? AND st.transaction_type IN ('issue_jobcard','return')
        ORDER BY st.transaction_date
    ");
    $stStmt->execute([$jobCardId]);
    $stockItems = $stStmt->fetchAll();
    $consumablesCost = 0;
    foreach ($stockItems as $si) {
        $mult = $si['transaction_type'] === 'return' ? -1 : 1;
        $consumablesCost += $mult * (float) $si['unit_cost'] * (float) $si['quantity'];
    }

    // ── Slips ────────────────────────────────────────────────
    $slStmt = $db->prepare("SELECT s.*, u.full_name AS captured_by FROM slips s LEFT JOIN users u ON u.id = s.user_id WHERE s.job_card_id=? ORDER BY s.slip_date");
    $slStmt->execute([$jobCardId]);
    $slips = $slStmt->fetchAll();
    $slipsTotal = array_sum(array_column($slips, 'amount'));

    $totalCost = $totalLabourCost + $travelCost + $consumablesCost + $slipsTotal;

    apiSuccess([
        'job_card' => $card,
        'labour' => array_values($techHours),
        'travel' => [
            'odo_start' => $odoStart,
            'odo_end' => $odoEnd,
            'km_travelled' => $kmTravelled,
            'cost_per_km' => $costPerKm,
            'quote_per_km' => $quotePerKm,
            'travel_cost' => round($travelCost, 2),
            'travel_quote' => round($travelQuote, 2),
            'vehicle' => $card['vehicle_reg'] ? $card['vehicle_make'] . ' ' . $card['vehicle_model'] . ' (' . $card['vehicle_reg'] . ')' : null,
        ],
        'consumables' => $stockItems,
        'slips' => $slips,
        'summary' => [
            'labour_cost' => round($totalLabourCost, 2),
            'travel_cost' => round($travelCost, 2),
            'consumables_cost' => round($consumablesCost, 2),
            'slips_total' => round($slipsTotal, 2),
            'total_cost' => round($totalCost, 2),
        ],
    ]);
} catch (Exception $e) {
    apiError('Error: ' . $e->getMessage(), 500);
}