<?php
declare(strict_types=1);

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

require_login($conn);

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

process_post_only_or_redirect('../pages/member.php?view=list');

$customerId = (int) (filter_input(INPUT_POST, 'customer_id', FILTER_VALIDATE_INT) ?: 0);
$view = strtolower(trim((string) ($_POST['view'] ?? 'list')));
$view = $view === 'profile' ? 'profile' : 'list';
$search = trim((string) ($_POST['q'] ?? ''));
$group = customer_group_filter_value((string) ($_POST['group'] ?? 'all'));
$name = trim((string) ($_POST['name'] ?? ''));
$phone = trim((string) ($_POST['phone'] ?? ''));
$normalizedPhone = normalize_phone($phone);
$email = trim((string) ($_POST['email'] ?? ''));
$customerGroup = customer_group_key((string) ($_POST['customer_group'] ?? 'member'));

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

$formQuery = $listQuery;
$formQuery['customer_id'] = $customerId;
$formQuery['edit'] = 1;
$formPath = '../pages/member.php?' . http_build_query($formQuery) . '#member-edit-form';

if ($customerId <= 0 || $name === '') {
    redirect_with_flash($formPath, 'error', localized_flash_message('กรุณาระบุชื่อลูกค้า', 'Customer name is required.'), $_POST);
}

$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.'));
}

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

$conn->begin_transaction();

try {
    $updateStmt = db_prepare($conn, "
        UPDATE customers
        SET
            name = ?,
            phone = ?,
            normalized_phone = ?,
            email = ?,
            customer_group = ?
        WHERE customer_id = ?
        LIMIT 1
    ");
    $updateStmt->bind_param('sssssi', $name, $phone, $normalizedPhone, $email, $customerGroup, $customerId);
    $updateStmt->execute();
    $updateStmt->close();

    $afterSnapshot = array(
        'name' => $name,
        'phone' => $phone,
        'email' => $email,
        'customer_group' => $customerGroup,
    );

    $diff = audit_diff_assoc($beforeSnapshot, $afterSnapshot);
    if (!empty($diff['after'])) {
        audit_log($conn, array(
            'module_key' => 'customer',
            'action_key' => 'update',
            'entity_type' => 'customer',
            'entity_id' => $customerId,
            'customer_id' => $customerId,
            'message' => 'Member record updated.',
            'before' => $diff['before'],
            'after' => $diff['after'],
        ));
    }

    $conn->commit();
    redirect_with_flash($listPath, 'success', localized_flash_message('บันทึกสมาชิกเรียบร้อยแล้ว', 'Member saved.'));
} catch (Throwable $exception) {
    process_handle_exception_and_redirect(
        $conn,
        $exception,
        'save_member',
        $formPath,
        localized_flash_message('บันทึกสมาชิกไม่สำเร็จ', 'Member was not saved.'),
        array(
            'customer_id' => $customerId,
            'view' => $view,
            'group' => $group,
            'customer_group' => $customerGroup,
        ),
        $_POST
    );
}
