<?php
// deleteCustomer.php

include '../../config.php'; // Hakikisha file ya config inajumuisha connection ya $conn

$customer_id = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;

if ($customer_id <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid customer id']);
    exit;
}

// Anza transaction
$conn->begin_transaction();

try {
    // 1. Futa loan collections zinazohusiana na mikopo ya mteja
    $sql = "DELETE lc FROM loans_collection lc 
            INNER JOIN loans l ON lc.loan_id = l.loan_id 
            WHERE l.customer_id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("i", $customer_id);
        $stmt->execute();
        $stmt->close();
    }

    // 2. Futa loan schedules zinazohusiana na mikopo ya mteja
    $sql = "DELETE ls FROM loans_schedule ls 
            INNER JOIN loans l ON ls.loan_id = l.loan_id 
            WHERE l.customer_id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("i", $customer_id);
        $stmt->execute();
        $stmt->close();
    }

    // 3. Futa mikopo ya mteja
    $sql = "DELETE FROM loans WHERE customer_id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("i", $customer_id);
        $stmt->execute();
        $stmt->close();
    }

    // 4. Futa rekodi ya mteja
    $sql = "DELETE FROM customers WHERE id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("i", $customer_id);
        $stmt->execute();
        $stmt->close();
    }

    // Commit transaction
    $conn->commit();

    echo json_encode(['status' => 'success', 'message' => 'Customer and related data deleted successfully']);
} catch (Exception $e) {
    // Rollback transaction ikiwa kuna tatizo
    $conn->rollback();
    echo json_encode(['status' => 'error', 'message' => 'Deletion failed: ' . $e->getMessage()]);
}
?>
