<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

// Tunatumia timezone Dar es Salaam
date_default_timezone_set('Africa/Dar_es_Salaam');
include '../config.php';  // Hakikisha hii ina-includa DB connection ($conn)

// Chukua GET au POST parameter (tumia GET hapa ili iwe rahisi kwa Flutter-ish)
$customer_id = isset($_GET['customer_id']) ? $_GET['customer_id'] : '';
$branch_id   = isset($_GET['branch_id'])   ? $_GET['branch_id']   : '';

// Validate required fields
if ($customer_id === '' || $branch_id === '') {
    echo json_encode([
      'status'  => 'error',
      'message' => 'Missing required fields: customer_id or branch_id'
    ]);
    exit;
}

// Tunataka kuangalia COUNT ya rows katika fines ambapo customer_id = ?
// na tarehe imeweka leo (sisi tumetumia column yako ya `date` kama DATE au DATETIME).
// Ikiwa column yako ni DATETIME, tutatumia DATE(date) = CURDATE().
// Pia, optional, tuna-fence kwa branch_id

$sql = "
  SELECT COUNT(*) AS cnt 
    FROM fines 
   WHERE customer_id = ? 
     AND branch_id   = ? 
     AND DATE(`date`) = CURDATE()
";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $customer_id, $branch_id);
$stmt->execute();
$stmt->bind_result($cnt);
$stmt->fetch();
$stmt->close();

// Jibu JSON: exists = 1 kama cnt > 0, vinginevyo 0.
echo json_encode([
  'status' => 'success',
  'exists' => ($cnt > 0 ? 1 : 0),
  'count'  => $cnt
]);

$conn->close();
?>
