<?php 
include '../includes/config.php';

if (isset($_REQUEST['del'])) {
    $id = intval($_GET['del']);

    $checkSql = "SELECT COUNT(*) FROM stock_sale WHERE customer_id = :id";
    $checkQuery = $conn->prepare($checkSql);
    $checkQuery->bindParam(':id', $id, PDO::PARAM_INT);
    $checkQuery->execute();
    $saleCount = $checkQuery->fetchColumn();

    if ($saleCount > 0) {
        echo "<script>alert('Cannot delete customer. Sales records exist.');</script>";
        echo "<script>window.location.href='../list_customers.php'</script>";
        exit;
    }

    $sql = "DELETE FROM contacts WHERE id = :id";
    $query = $conn->prepare($sql);
    $query->bindParam(':id', $id, PDO::PARAM_INT);
    $query->execute();

    $count = $query->rowCount();
    if ($count > 0) {
        echo "<script>alert('Customer deleted successfully.');</script>";
    } else {
        echo "<script>alert('No customer found to delete.');</script>";
    }

    echo "<script>window.location.href='../list_customers.php'</script>";
}
?>
