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

// Set timezone ya Dar es Salaam
date_default_timezone_set('Africa/Dar_es_Salaam');
include '../config.php';

// Chukua POST parameters
$amount       = isset($_POST['amount'])      ? $_POST['amount']      : '';
$description  = isset($_POST['description']) ? $_POST['description'] : '';
// Hapa tunatumia default kama haijatumwa (tarehe+time)
$date         = isset($_POST['date'])        ? $_POST['date']        : date('Y-m-d H:i:s');
$loan_id      = isset($_POST['loan_id'])     ? $_POST['loan_id']     : '';
$customer_id  = isset($_POST['customer_id']) ? $_POST['customer_id'] : '';
$branch_id    = isset($_POST['branch_id'])   ? $_POST['branch_id']   : '';
$status       = isset($_POST['status'])      ? $_POST['status']      : '';

// Halali au Hapana?
if ($amount === '' || $loan_id === '' || $customer_id === '' || $branch_id === '') {
    echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
    exit;
}

// ================== Tumia prepare/bind sahihi ==================
// Hakikisha kolamu zako kwenye DB ndo: amount (DECIMAL/DOUBLE), description (VARCHAR),
// date (DATETIME au DATE), loan_id (INT), customer_id (INT), branch_id (INT), status (INT).

$stmt = $conn->prepare("
    INSERT INTO fines 
      (amount, description, date, loan_id, customer_id, branch_id, status) 
    VALUES (?, ?, ?, ?, ?, ?, ?)
");
// Aina za parameters: 
//  d = double (amount)
//  s = string (description)
//  s = string (date)  <-- endapo kolamu ni DATETIME, inabidi iwe 'Y-m-d H:i:s'
//  i = int (loan_id)
//  i = int (customer_id)
//  i = int (branch_id)
//  i = int (status)
$stmt->bind_param(
    "dssiiii", 
    $amount, 
    $description, 
    $date, 
    $loan_id, 
    $customer_id, 
    $branch_id, 
    $status
);

if ($stmt->execute()) {
    echo json_encode(['status' => 'success', 'message' => 'Fine added successfully']);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Failed to insert: ' . $stmt->error]);
}

$stmt->close();
$conn->close();
?>
