<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/bootstrap.php';

require_login($conn);

if (!can_access($conn, 'member_manage') || !can_access($conn, 'member_delete')) {
    redirect_with_flash(auth_page_path(auth_preferred_landing_page($conn)), 'error', localized_flash_message('คุณไม่มีสิทธิ์ใช้งานฟังก์ชันนี้', 'You do not have permission to access that function.'));
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect('../pages/member.php?view=list');
}

$customerId = (int) (filter_input(INPUT_POST, 'customer_id', FILTER_VALIDATE_INT) ?: 0);
$search = trim((string) ($_POST['q'] ?? ''));
$group = customer_group_filter_value((string) ($_POST['group'] ?? 'all'));

$listQuery = array('view' => 'list');
if ($search !== '') {
    $listQuery['q'] = $search;
}
if ($group !== 'all') {
    $listQuery['group'] = $group;
}
$listPath = '../pages/member.php?' . http_build_query($listQuery);

if ($customerId <= 0) {
    redirect_with_flash($listPath, 'error', localized_flash_message('ไม่พบสมาชิก', 'Member was not found.'));
}

$accessTypes = '';
$accessParams = array();
$accessJoin = "INNER JOIN orders o ON o.customer_id = c.customer_id AND o.status <> 'cancelled'";
$branchCondition = auth_branch_condition($conn, 'o', $accessTypes, $accessParams);
if ($branchCondition !== '') {
    $accessJoin .= " AND {$branchCondition}";
}
$accessTypes .= 'i';
$accessParams[] = $customerId;

$snapshotStmt = db_prepare($conn, "
    SELECT
        c.customer_id,
        c.name,
        c.phone,
        c.email,
        c.customer_group
    FROM customers c
    {$accessJoin}
    WHERE c.customer_id = ?
    GROUP BY
        c.customer_id,
        c.name,
        c.phone,
        c.email,
        c.customer_group
    LIMIT 1
");
$snapshotStmt->bind_param($accessTypes, ...$accessParams);
$snapshotStmt->execute();
$customerSnapshot = $snapshotStmt->get_result()->fetch_assoc();
$snapshotStmt->close();

if (!$customerSnapshot) {
    redirect_with_flash($listPath, 'error', localized_flash_message('ไม่พบสมาชิก', 'Member was not found.'));
}

$orderCountStmt = db_prepare($conn, "
    SELECT COUNT(*) AS total_rows
    FROM orders
    WHERE customer_id = ?
");
$orderCountStmt->bind_param('i', $customerId);
$orderCountStmt->execute();
$orderCount = (int) (($orderCountStmt->get_result()->fetch_assoc()['total_rows'] ?? 0));
$orderCountStmt->close();

$packageCountStmt = db_prepare($conn, "
    SELECT COUNT(*) AS total_rows
    FROM customer_packages
    WHERE customer_id = ?
");
$packageCountStmt->bind_param('i', $customerId);
$packageCountStmt->execute();
$packageCount = (int) (($packageCountStmt->get_result()->fetch_assoc()['total_rows'] ?? 0));
$packageCountStmt->close();

$loyaltyCountStmt = db_prepare($conn, "
    SELECT COUNT(*) AS total_rows
    FROM loyalty_transactions
    WHERE customer_id = ?
");
$loyaltyCountStmt->bind_param('i', $customerId);
$loyaltyCountStmt->execute();
$loyaltyCount = (int) (($loyaltyCountStmt->get_result()->fetch_assoc()['total_rows'] ?? 0));
$loyaltyCountStmt->close();

if ($orderCount > 0 || $packageCount > 0 || $loyaltyCount > 0) {
    redirect_with_flash($listPath, 'error', localized_flash_message('ไม่สามารถลบสมาชิกได้ เพราะยังมีประวัติบริการ แพ็กเกจ หรือสะสมแต้มคงอยู่', 'Member cannot be deleted because service, package or loyalty history still exists.'));
}

$beforeSnapshot = array(
    'customer_id' => $customerId,
    'name' => (string) ($customerSnapshot['name'] ?? ''),
    'phone' => (string) ($customerSnapshot['phone'] ?? ''),
    'email' => (string) ($customerSnapshot['email'] ?? ''),
    'customer_group' => (string) ($customerSnapshot['customer_group'] ?? 'member'),
);

$conn->begin_transaction();

try {
    $deleteCarsStmt = db_prepare($conn, "
        DELETE FROM cars
        WHERE customer_id = ?
    ");
    $deleteCarsStmt->bind_param('i', $customerId);
    $deleteCarsStmt->execute();
    $deletedCars = $deleteCarsStmt->affected_rows;
    $deleteCarsStmt->close();

    $deleteCustomerStmt = db_prepare($conn, "
        DELETE FROM customers
        WHERE customer_id = ?
        LIMIT 1
    ");
    $deleteCustomerStmt->bind_param('i', $customerId);
    $deleteCustomerStmt->execute();
    $deleteCustomerStmt->close();

    audit_log($conn, array(
        'module_key' => 'customer',
        'action_key' => 'delete',
        'entity_type' => 'customer',
        'entity_id' => $customerId,
        'customer_id' => $customerId,
        'message' => 'Member record deleted.',
        'before' => $beforeSnapshot,
        'meta' => array(
            'deleted_cars' => $deletedCars,
        ),
    ));

    $conn->commit();
    redirect_with_flash($listPath, 'success', localized_flash_message('ลบสมาชิกเรียบร้อยแล้ว', 'Member deleted.'));
} catch (Throwable $exception) {
    $conn->rollback();
    redirect_with_flash($listPath, 'error', localized_flash_message('ลบสมาชิกไม่สำเร็จ', 'Member could not be deleted.'));
}
