<?php
include 'layouts/session.php';
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Check if ID parameter exists
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "No customer ID provided";
    header("Location: all_customers.php");
    exit();
}

$customerId = intval($_GET['id']);

try {
    // Begin transaction
    $conn->begin_transaction();
    
    // Soft delete - Update status to 0 (inactive)
    // For a hard delete, use: "DELETE FROM customers WHERE customer_id = ?"
    $query = "UPDATE customers SET status = 0 WHERE customer_id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $customerId);
    
    if ($stmt->execute()) {
        // Commit the transaction
        $conn->commit();
        $_SESSION['success_message'] = "Customer has been deleted successfully";
    } else {
        // Rollback the transaction
        $conn->rollback();
        $_SESSION['error_message'] = "Error deleting customer: " . $stmt->error;
    }
    
} catch (Exception $e) {
    // Rollback the transaction
    $conn->rollback();
    $_SESSION['error_message'] = "Error deleting customer: " . $e->getMessage();
}

// Redirect back to customer list
header("Location: all_customers.php");
exit();
?>