<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../includes/db.php';

// 🔐 Extract token from header
$headers = getallheaders();
$token = $headers['Authorization'] ?? '';

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'Missing token']);
    exit;
}

// 🔐 Validate token
$stmt = $pdo->prepare("SELECT * FROM users WHERE token = ?");
$stmt->execute([$token]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    http_response_code(403);
    echo json_encode(['error' => 'Invalid token']);
    exit;
}

$today = date('Y-m-d');
$startOfWeek = date('Y-m-d', strtotime('monday this week'));
$endOfWeek = date('Y-m-d', strtotime('sunday this week'));

$response = [
    'success' => true,
    'late_deliveries' => [],
    'due_this_week' => [],
    'others' => []
];

// 📦 Fetch Late Deliveries
$stmt = $pdo->prepare("
    SELECT b.bill_id, b.bill_number, b.in_date, b.required_date, b.status, b.ready_sms_sent,
           c.name, c.contact_number,
           COALESCE((SELECT SUM(j.total) FROM jobs j WHERE j.bill_id = b.bill_id), 0) AS grand_total,
           COALESCE((SELECT SUM(p.amount) FROM payments p WHERE p.bill_id = b.bill_id), 0) AS total_paid
    FROM bills b
    JOIN customers c ON b.customer_id = c.customer_id
    WHERE b.status = 'Pending' AND b.required_date < ?
    ORDER BY b.required_date ASC
");
$stmt->execute([$today]);
$response['late_deliveries'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
$lateIds = array_column($response['late_deliveries'], 'bill_id');

// 📦 Fetch Due This Week
$stmt = $pdo->prepare("
    SELECT b.bill_id, b.bill_number, b.in_date, b.required_date, b.status, b.ready_sms_sent,
           c.name, c.contact_number,
           COALESCE((SELECT SUM(j.total) FROM jobs j WHERE j.bill_id = b.bill_id), 0) AS grand_total,
           COALESCE((SELECT SUM(p.amount) FROM payments p WHERE p.bill_id = b.bill_id), 0) AS total_paid
    FROM bills b
    JOIN customers c ON b.customer_id = c.customer_id
    WHERE b.status = 'Pending' AND b.required_date BETWEEN ? AND ?
    ORDER BY b.required_date ASC
");
$stmt->execute([$startOfWeek, $endOfWeek]);
$response['due_this_week'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
$weekIds = array_column($response['due_this_week'], 'bill_id');

// 📦 Fetch Other Pending Bills
$stmt = $pdo->query("
    SELECT b.bill_id, b.bill_number, b.in_date, b.required_date, b.status, b.ready_sms_sent,
           c.name, c.contact_number,
           COALESCE((SELECT SUM(j.total) FROM jobs j WHERE j.bill_id = b.bill_id), 0) AS grand_total,
           COALESCE((SELECT SUM(p.amount) FROM payments p WHERE p.bill_id = b.bill_id), 0) AS total_paid
    FROM bills b
    JOIN customers c ON b.customer_id = c.customer_id
    WHERE b.status = 'Pending'
    ORDER BY b.in_date DESC
");
$allBills = $stmt->fetchAll(PDO::FETCH_ASSOC);

$response['others'] = array_filter($allBills, function ($bill) use ($lateIds, $weekIds) {
    return !in_array($bill['bill_id'], $lateIds) && !in_array($bill['bill_id'], $weekIds);
});

echo json_encode($response);
