<?php
// POST /api/slips/list.php
// Returns both expense slips AND fleet fuel costs unified
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user   = requireAuth();
$db     = getDB();
$p      = getPagination();
$myOnly   = post('my_only', '');
$status   = post('status', '');
$dateFrom = post('date_from', '');
$dateTo   = post('date_to', '');

// Default to current month if no dates provided
if (!$dateFrom && !$dateTo) {
    $dateFrom = date('Y-m-01');
    $dateTo   = date('Y-m-d');
}

// Build WHERE for slips
$slipWhere  = ['1=1'];
$slipParams = [];
if ($myOnly || !in_array($user['role_id'], [1, 5])) {
    $slipWhere[] = 's.user_id = ?';
    $slipParams[] = $user['id'];
}
if ($dateFrom) { $slipWhere[] = 's.slip_date >= ?'; $slipParams[] = $dateFrom; }
if ($dateTo)   { $slipWhere[] = 's.slip_date <= ?'; $slipParams[] = $dateTo; }

// Fleet fuel costs WHERE
$fuelWhere  = ["fc.cost_type = 'fuel'"];
$fuelParams = [];
if ($myOnly || !in_array($user['role_id'], [1, 5])) {
    $fuelWhere[] = 'fc.created_by = ?';
    $fuelParams[] = $user['id'];
}
if ($dateFrom) { $fuelWhere[] = 'fc.cost_date >= ?'; $fuelParams[] = $dateFrom; }
if ($dateTo)   { $fuelWhere[] = 'fc.cost_date <= ?'; $fuelParams[] = $dateTo; }

// If filtering by 'fuel', only show fleet costs; otherwise include both
$showFuelOnly = ($status === 'fuel');
$showSlips    = !$showFuelOnly;
$showFuel     = ($status === '' || $status === 'fuel');

// Status filter for slips (not applicable to fuel)
if ($status && $status !== 'fuel') {
    $slipWhere[] = 's.status = ?';
    $slipParams[] = $status;
}

$slipWhereStr = implode(' AND ', $slipWhere);
$fuelWhereStr = implode(' AND ', $fuelWhere);

// Build combined query
$parts  = [];
$params = [];

if ($showSlips) {
    $parts[] = "
        SELECT
            s.id, s.slip_date, s.merchant, s.category, s.amount, s.vat_amount,
            s.payment_method, s.description, s.filename, s.original_name, s.status,
            s.job_card_id, s.project_id, s.user_id,
            IF(s.filename IS NOT NULL, CONCAT('uploads/slips/', s.filename), NULL) AS image_path,
            s.created_at,
            u.full_name AS user_name,
            p.name AS project_name,
            jc.job_number,
            NULL AS vehicle_reg,
            'slip' AS source_type
        FROM slips s
        JOIN users u ON u.id = s.user_id
        LEFT JOIN projects p ON p.id = s.project_id
        LEFT JOIN job_cards jc ON jc.id = s.job_card_id
        WHERE $slipWhereStr";
    $params = array_merge($params, $slipParams);
}

if ($showFuel) {
    $parts[] = "
        SELECT
            fc.id, fc.cost_date AS slip_date, v.registration AS merchant,
            'fuel' AS category, fc.amount, NULL AS vat_amount,
            'card' AS payment_method, fc.description,
            fc.slip_filename AS filename,
            NULL AS original_name,
            'fuel' AS status,
            NULL AS job_card_id, NULL AS project_id, fc.created_by AS user_id,
            fc.slip_image_path AS image_path,
            fc.created_at,
            u.full_name AS user_name,
            NULL AS project_name,
            NULL AS job_number,
            v.registration AS vehicle_reg,
            'fuel' AS source_type
        FROM fleet_costs fc
        JOIN fleet_vehicles v ON v.id = fc.vehicle_id
        LEFT JOIN users u ON u.id = fc.created_by
        WHERE $fuelWhereStr";
    $params = array_merge($params, $fuelParams);
}

if (empty($parts)) {
    apiSuccess(['slips' => [], 'pagination' => ['total'=>0,'page'=>1,'limit'=>25,'pages'=>0]]);
}

$union = implode(' UNION ALL ', $parts);

// Count total
$countStmt = $db->prepare("SELECT COUNT(*) FROM ($union) AS combined");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();

// Paginated results
$stmt = $db->prepare("
    SELECT * FROM ($union) AS combined
    ORDER BY slip_date DESC, created_at DESC
    LIMIT {$p['limit']} OFFSET {$p['offset']}
");
$stmt->execute($params);

apiSuccess([
    'slips'      => $stmt->fetchAll(),
    'pagination' => ['total'=>$total,'page'=>$p['page'],'limit'=>$p['limit'],'pages'=>ceil($total/$p['limit'])]
]);