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

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

// Check if necessary parameters are set
if (!isset($_GET['id']) || !isset($_GET['status'])) {
    $_SESSION['error_message'] = "Missing required parameters";
    header("Location: cust_customer_list.php");
    exit();
}

$customer_id = intval($_GET['id']);
$status = intval($_GET['status']);

// Validate parameters
if ($customer_id <= 0) {
    $_SESSION['error_message'] = "Invalid customer ID";
    header("Location: cust_customer_list.php");
    exit();
}

if ($status !== 0 && $status !== 1) {
    $_SESSION['error_message'] = "Invalid status value";
    header("Location: customer_view.php?id=" . $customer_id);
    exit();
}

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Update customer status
    $query = "UPDATE customers SET status = ? WHERE customer_id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("ii", $status, $customer_id);
    
    if (!$stmt->execute()) {
        throw new Exception("Error updating customer status: " . $stmt->error);
    }
    
    // Commit transaction
    $conn->commit();
    
    $statusText = ($status == 1) ? "activated" : "deactivated";
    $_SESSION['success_message'] = "Customer successfully " . $statusText;
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    $_SESSION['error_message'] = $e->getMessage();
}

// Redirect back to customer view
header("Location: customer_view.php?id=" . $customer_id);
exit();
?>