<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require 'db_config.php';

if (!isset($pdo)) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Database connection failed"]);
    exit();
}

$id = $_POST['id'] ?? null;
$customer_name = $_POST['customer_name'] ?? '';
$mobile_number = $_POST['mobile_number'] ?? '';
$amount = $_POST['amount'] ?? 0;
$bill_no = $_POST['bill_no'] ?? '';
$bill_date = $_POST['bill_date'] ?? '';
$status = $_POST['status'] ?? 'Unpaid';

try {
    if ($id) {
        $stmt = $pdo->prepare("UPDATE dues SET customer_name=?, mobile_number=?, amount=?, bill_no=?, bill_date=?, status=? WHERE id=?");
        $stmt->execute([$customer_name, $mobile_number, $amount, $bill_no, $bill_date, $status, $id]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO dues (customer_name, mobile_number, amount, bill_no, bill_date, status) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$customer_name, $mobile_number, $amount, $bill_no, $bill_date, $status]);
    }
    echo json_encode(["status" => "success", "message" => "Operation successful"]);
} catch (PDOException $e) {
    echo json_encode(["status" => "error", "message" => "Database error: " . $e->getMessage()]);
}
?>