<?php
require_once 'config.inc.php';
require_login();

/*
|--------------------------------------------------------------------------
| AJAX/API HANDLERS
|--------------------------------------------------------------------------
| This keeps the popup functionality inside users.php, so you do not need
| a separate user_popup.php file.
*/

function json_response(array $data, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function post_string_value(string $key, string $default = ''): string
{
    return isset($_POST[$key]) ? trim((string)$_POST[$key]) : $default;
}

function post_int_value(string $key, int $default = 0): int
{
    return isset($_POST[$key]) ? (int)$_POST[$key] : $default;
}

function post_float_value(string $key, float $default = 0): float
{
    return isset($_POST[$key]) ? (float)$_POST[$key] : $default;
}

/*
|--------------------------------------------------------------------------
| AJAX USER DETAILS
|--------------------------------------------------------------------------
*/
if (($_GET['ajax'] ?? '') === 'user_details') {
    $userId = (int)($_GET['user_id'] ?? 0);

    if ($userId <= 0) {
        json_response(['success' => false, 'message' => 'Invalid user ID.'], 400);
    }

    $db = db();

    $s = $db->prepare("
        SELECT id, full_name, phone, email, address, account_status, status, created_at
        FROM users
        WHERE id = ?
        LIMIT 1
    ");
    $s->bind_param("i", $userId);
    $s->execute();
    $user = $s->get_result()->fetch_assoc();
    $s->close();

    if (!$user) {
        json_response(['success' => false, 'message' => 'User not found.'], 404);
    }

    $orders = [];

    $s = $db->prepare("
        SELECT id, total_amount, created_at, status, COALESCE(admin_comment, '') AS admin_comment
        FROM orders
        WHERE user_id = ?
        ORDER BY id DESC
    ");
    $s->bind_param("i", $userId);
    $s->execute();
    $ordersResult = $s->get_result();

    while ($order = $ordersResult->fetch_assoc()) {
        $orderId = (int)$order['id'];
        $order['id'] = $orderId;
        $order['total_amount'] = (float)$order['total_amount'];
        $order['items'] = [];

        $itemStmt = $db->prepare("
            SELECT
                oi.id,
                oi.product_id,
                oi.quantity,
                oi.quantity_delivered,
                oi.unit_price,
                oi.subtotal,
                p.display_model,
                COALESCE(b.name, '') AS product_brand,
                COALESCE(dt.name, '') AS display_type,
                COALESCE((
                    SELECT SUM(r.quantity)
                    FROM order_returns r
                    WHERE r.order_item_id = oi.id
                ), 0) AS returned_quantity,
                COALESCE((
                    SELECT SUM(r.total_amount)
                    FROM order_returns r
                    WHERE r.order_item_id = oi.id
                ), 0) AS returned_amount
            FROM order_items oi
            LEFT JOIN products p ON p.id = oi.product_id
            LEFT JOIN brands b ON b.id = p.brand_id
            LEFT JOIN display_types dt ON dt.id = oi.display_type_id
            WHERE oi.order_id = ?
            ORDER BY oi.id ASC
        ");
        $itemStmt->bind_param("i", $orderId);
        $itemStmt->execute();
        $itemsResult = $itemStmt->get_result();

        while ($item = $itemsResult->fetch_assoc()) {
            $item['id'] = (int)$item['id'];
            $item['product_id'] = (int)$item['product_id'];
            $item['quantity'] = (int)$item['quantity'];
            $item['quantity_delivered'] = (int)$item['quantity_delivered'];
            $item['returned_quantity'] = (int)$item['returned_quantity'];
            $item['unit_price'] = (float)$item['unit_price'];
            $item['subtotal'] = (float)$item['subtotal'];
            $item['returned_amount'] = (float)$item['returned_amount'];
            $deliveredForReturn = $item['quantity_delivered'] > 0
                ? $item['quantity_delivered']
                : $item['quantity'];
            $item['available_return_qty'] = max(
                0,
                $deliveredForReturn - $item['returned_quantity']
            );

            $description = trim(
                $item['product_brand'] . ' ' . ($item['display_model'] ?? '')
            );
            if ($description === '') {
                $description = 'Product #' . $item['product_id'];
            }

            if ($item['display_type'] !== '') {
                $description .= ' - ' . $item['display_type'];
            }

            $item['description'] = $description;
            $order['items'][] = $item;
        }

        $itemStmt->close();
        $orders[] = $order;
    }

    $s->close();

    /* Payments */
    $payments = [];
    $receivedTotal = 0.00;

    $s = $db->prepare("
        SELECT
            id,
            order_id,
            amount,
            payment_date,
            payment_method,
            COALESCE(reference_no, '') AS reference_no,
            COALESCE(notes, '') AS notes
        FROM user_payments
        WHERE user_id = ?
        ORDER BY payment_date DESC, id DESC
    ");
    $s->bind_param("i", $userId);
    $s->execute();
    $paymentResult = $s->get_result();

    while ($payment = $paymentResult->fetch_assoc()) {
        $payment['id'] = (int)$payment['id'];
        $payment['order_id'] = $payment['order_id'] !== null ? (int)$payment['order_id'] : null;
        $payment['amount'] = (float)$payment['amount'];
        $receivedTotal += $payment['amount'];
        $payments[] = $payment;
    }

    $s->close();

    /* Returns */
    $returns = [];
    $returnedTotal = 0.00;

    $s = $db->prepare("
        SELECT
            r.id,
            r.order_id,
            r.order_item_id,
            r.quantity,
            r.unit_price,
            r.total_amount,
            r.return_date,
            COALESCE(r.reason, '') AS reason,
            COALESCE(r.notes, '') AS notes,
            COALESCE(p.display_model, '') AS display_model,
            COALESCE(b.name, '') AS product_brand
        FROM order_returns r
        INNER JOIN order_items oi ON oi.id = r.order_item_id
        INNER JOIN products p ON p.id = oi.product_id
        LEFT JOIN brands b ON b.id = p.brand_id
        WHERE r.user_id = ?
        ORDER BY r.return_date DESC, r.id DESC
    ");
    $s->bind_param("i", $userId);
    $s->execute();
    $returnResult = $s->get_result();

    while ($return = $returnResult->fetch_assoc()) {
        $return['id'] = (int)$return['id'];
        $return['order_id'] = (int)$return['order_id'];
        $return['order_item_id'] = (int)$return['order_item_id'];
        $return['quantity'] = (int)$return['quantity'];
        $return['unit_price'] = (float)$return['unit_price'];
        $return['total_amount'] = (float)$return['total_amount'];
        $returnedTotal += $return['total_amount'];

        $return['description'] = trim(
            $return['product_brand'] . ' ' . $return['display_model']
        );

        $returns[] = $return;
    }

    $s->close();

    /* Warranties */
    $warranties = [];

    $s = $db->prepare("
        SELECT
            w.id,
            w.order_id,
            w.order_item_id,
            w.warranty_title,
            w.warranty_start,
            w.warranty_end,
            w.warranty_status,
            COALESCE(w.notes, '') AS notes,
            COALESCE(p.display_model, '') AS display_model,
            COALESCE(b.name, '') AS product_brand
        FROM user_warranties w
        LEFT JOIN order_items oi ON oi.id = w.order_item_id
        LEFT JOIN products p ON p.id = oi.product_id
        LEFT JOIN brands b ON b.id = p.brand_id
        WHERE w.user_id = ?
        ORDER BY w.warranty_end DESC, w.id DESC
    ");
    $s->bind_param("i", $userId);
    $s->execute();
    $warrantyResult = $s->get_result();

    while ($warranty = $warrantyResult->fetch_assoc()) {
        $warranty['id'] = (int)$warranty['id'];
        $warranties[] = $warranty;
    }

    $s->close();

    $grossTotal = 0.00;
    foreach ($orders as $order) {
        $grossTotal += (float)$order['total_amount'];
    }

    /*
     * Returns reduce the amount owed.
     * Balance > 0  = customer still owes money.
     * Balance < 0  = customer has credit/refund due.
     */
    $netTotal = $grossTotal - $returnedTotal;
    $balance = $netTotal - $receivedTotal;

    json_response([
        'success' => true,
        'user' => $user,
        'orders' => $orders,
        'payments' => $payments,
        'returns' => $returns,
        'warranties' => $warranties,
        'summary' => [
            'gross_total' => round($grossTotal, 2),
            'returned_total' => round($returnedTotal, 2),
            'net_total' => round($netTotal, 2),
            'received_total' => round($receivedTotal, 2),
            'balance' => round($balance, 2)
        ]
    ]);
}

/*
|--------------------------------------------------------------------------
| AJAX POST ACTIONS
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
    check_csrf();

    $action = $_POST['ajax_action'];
    $userId = post_int_value('user_id');

    if ($userId <= 0) {
        json_response(['success' => false, 'message' => 'Invalid user ID.'], 400);
    }

    $db = db();

    /* Verify user exists */
    $checkUser = $db->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
    $checkUser->bind_param("i", $userId);
    $checkUser->execute();
    $exists = $checkUser->get_result()->fetch_assoc();
    $checkUser->close();

    if (!$exists) {
        json_response(['success' => false, 'message' => 'User not found.'], 404);
    }

    /*
    |--------------------------------------------------------------------------
    | ADD PAYMENT
    |--------------------------------------------------------------------------
    */
    if ($action === 'add_payment') {
        $amount = post_float_value('amount');
        $orderId = post_int_value('order_id');
        $paymentDate = post_string_value('payment_date');
        $paymentMethod = post_string_value('payment_method', 'Cash');
        $referenceNo = post_string_value('reference_no');
        $notes = post_string_value('notes');

        if ($amount <= 0) {
            json_response(['success' => false, 'message' => 'Enter a valid received amount.'], 400);
        }

        if ($paymentDate === '') {
            $paymentDate = date('Y-m-d H:i:s');
        } elseif (strlen($paymentDate) === 16) {
            $paymentDate = str_replace('T', ' ', $paymentDate) . ':00';
        }

        if ($orderId > 0) {
            $check = $db->prepare("
                SELECT id
                FROM orders
                WHERE id = ? AND user_id = ?
                LIMIT 1
            ");
            $check->bind_param("ii", $orderId, $userId);
            $check->execute();
            $validOrder = $check->get_result()->fetch_assoc();
            $check->close();

            if (!$validOrder) {
                json_response([
                    'success' => false,
                    'message' => 'Selected order does not belong to this user.'
                ], 400);
            }
        } else {
            $orderId = null;
        }

        $adminId = isset($_SESSION['admin_id']) ? (int)$_SESSION['admin_id'] : null;

        $stmt = $db->prepare("
            INSERT INTO user_payments
                (user_id, order_id, amount, payment_date, payment_method,
                 reference_no, notes, created_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->bind_param(
            "iidssssi",
            $userId,
            $orderId,
            $amount,
            $paymentDate,
            $paymentMethod,
            $referenceNo,
            $notes,
            $adminId
        );

        if (!$stmt->execute()) {
            $message = $stmt->error;
            $stmt->close();
            json_response(['success' => false, 'message' => $message], 500);
        }

        $stmt->close();

        json_response([
            'success' => true,
            'message' => 'Received amount added successfully.'
        ]);
    }

    /*
    |--------------------------------------------------------------------------
    | ADD WARRANTY
    |--------------------------------------------------------------------------
    */
    if ($action === 'add_warranty') {
        $orderId = post_int_value('order_id');
        $orderItemId = post_int_value('order_item_id');
        $title = post_string_value('warranty_title', 'Standard Warranty');
        $start = post_string_value('warranty_start');
        $end = post_string_value('warranty_end');
        $notes = post_string_value('notes');

        if ($start === '' || $end === '') {
            json_response([
                'success' => false,
                'message' => 'Warranty start and end dates are required.'
            ], 400);
        }

        if ($end < $start) {
            json_response([
                'success' => false,
                'message' => 'Warranty end date cannot be before the start date.'
            ], 400);
        }

        if ($orderId > 0) {
            $check = $db->prepare("
                SELECT id FROM orders
                WHERE id = ? AND user_id = ?
                LIMIT 1
            ");
            $check->bind_param("ii", $orderId, $userId);
            $check->execute();
            $validOrder = $check->get_result()->fetch_assoc();
            $check->close();

            if (!$validOrder) {
                json_response(['success' => false, 'message' => 'Invalid order.'], 400);
            }
        } else {
            $orderId = null;
        }

        if ($orderItemId > 0) {
            $check = $db->prepare("
                SELECT oi.id
                FROM order_items oi
                INNER JOIN orders o ON o.id = oi.order_id
                WHERE oi.id = ? AND o.user_id = ?
                LIMIT 1
            ");
            $check->bind_param("ii", $orderItemId, $userId);
            $check->execute();
            $validItem = $check->get_result()->fetch_assoc();
            $check->close();

            if (!$validItem) {
                json_response(['success' => false, 'message' => 'Invalid order item.'], 400);
            }
        } else {
            $orderItemId = null;
        }

        $adminId = isset($_SESSION['admin_id']) ? (int)$_SESSION['admin_id'] : null;

        $stmt = $db->prepare("
            INSERT INTO user_warranties
                (user_id, order_id, order_item_id, warranty_title,
                 warranty_start, warranty_end, warranty_status, notes, created_by)
            VALUES (?, ?, ?, ?, ?, ?, 'active', ?, ?)
        ");

        $stmt->bind_param(
            "iiissssi",
            $userId,
            $orderId,
            $orderItemId,
            $title,
            $start,
            $end,
            $notes,
            $adminId
        );

        if (!$stmt->execute()) {
            $message = $stmt->error;
            $stmt->close();
            json_response(['success' => false, 'message' => $message], 500);
        }

        $stmt->close();

        json_response([
            'success' => true,
            'message' => 'Warranty added successfully.'
        ]);
    }

    /*
    |--------------------------------------------------------------------------
    | ADD RETURN
    |--------------------------------------------------------------------------
    | The server always reads the actual selling price from order_items.
    | Return total = unit price x returned quantity.
    | Returned quantity is added back to products stock.
    |--------------------------------------------------------------------------
    */
    if ($action === 'add_return') {
        $orderId = post_int_value('order_id');
        $orderItemId = post_int_value('order_item_id');
        $quantity = post_int_value('quantity');
        $reason = post_string_value('reason');
        $notes = post_string_value('notes');

        if ($orderId <= 0 || $orderItemId <= 0 || $quantity <= 0) {
            json_response([
                'success' => false,
                'message' => 'Order, item and return quantity are required.'
            ], 400);
        }

        $db->begin_transaction();

        try {
            $stmt = $db->prepare("
                SELECT
                    oi.id,
                    oi.order_id,
                    oi.product_id,
                    oi.quantity,
                    oi.quantity_delivered,
                    oi.unit_price,
                    COALESCE((
                        SELECT SUM(r.quantity)
                        FROM order_returns r
                        WHERE r.order_item_id = oi.id
                    ), 0) AS already_returned
                FROM order_items oi
                INNER JOIN orders o ON o.id = oi.order_id
                WHERE oi.id = ?
                  AND oi.order_id = ?
                  AND o.user_id = ?
                LIMIT 1
                FOR UPDATE
            ");

            $stmt->bind_param("iii", $orderItemId, $orderId, $userId);
            $stmt->execute();
            $item = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            if (!$item) {
                throw new Exception('Invalid order item.');
            }

            $alreadyReturned = (int)$item['already_returned'];
            $baseReturnQty = (int)$item['quantity_delivered'] > 0
                ? (int)$item['quantity_delivered']
                : (int)$item['quantity'];
            $available = max(0, $baseReturnQty - $alreadyReturned);

            if ($quantity > $available) {
                throw new Exception(
                    "Only {$available} item(s) are available for return."
                );
            }

            $unitPrice = (float)$item['unit_price'];
            $totalAmount = round($unitPrice * $quantity, 2);
            $productId = (int)$item['product_id'];
            $adminId = isset($_SESSION['admin_id']) ? (int)$_SESSION['admin_id'] : null;

            $stmt = $db->prepare("
                INSERT INTO order_returns
                    (user_id, order_id, order_item_id, quantity, unit_price,
                     total_amount, return_date, reason, notes, created_by)
                VALUES (?, ?, ?, ?, ?, ?, NOW(), ?, ?, ?)
            ");

            $stmt->bind_param(
                "iiiiddssi",
                $userId,
                $orderId,
                $orderItemId,
                $quantity,
                $unitPrice,
                $totalAmount,
                $reason,
                $notes,
                $adminId
            );

            if (!$stmt->execute()) {
                throw new Exception($stmt->error);
            }

            $stmt->close();

            /*
             * Put the returned product back into main stock.
             */
            $stockStmt = $db->prepare("
                UPDATE products
                SET quantity = quantity + ?
                WHERE id = ?
            ");
            $stockStmt->bind_param("ii", $quantity, $productId);

            if (!$stockStmt->execute()) {
                throw new Exception($stockStmt->error);
            }

            $stockStmt->close();

            /*
             * If stock_movements exists, record the return movement.
             */
            $movementStmt = $db->prepare("
                INSERT INTO stock_movements
                    (product_id, movement_type, quantity, reference_type,
                     reference_id, note, created_by)
                VALUES (?, 'IN', ?, 'RETURN', ?, ?, ?)
            ");

            if ($movementStmt) {
                $movementNote = 'Customer return';
                $returnId = (int)$db->insert_id;

                $movementStmt->bind_param(
                    "iiisi",
                    $productId,
                    $quantity,
                    $returnId,
                    $movementNote,
                    $adminId
                );
                $movementStmt->execute();
                $movementStmt->close();
            }

            $db->commit();

            json_response([
                'success' => true,
                'message' => 'Return recorded successfully.',
                'unit_price' => $unitPrice,
                'quantity' => $quantity,
                'total_amount' => $totalAmount
            ]);
        } catch (Throwable $e) {
            $db->rollback();

            json_response([
                'success' => false,
                'message' => $e->getMessage()
            ], 400);
        }
    }

    json_response(['success' => false, 'message' => 'Unknown AJAX action.'], 400);
}

/*
|--------------------------------------------------------------------------
| NORMAL USER MANAGEMENT ACTIONS
|--------------------------------------------------------------------------
*/

// Sanitize filter
$filter = $_GET['filter'] ?? 'all';
if (!in_array($filter, ['pending', 'approved', 'rejected'], true)) {
    $filter = 'all';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf();
    $op = $_POST['op'] ?? '';

    if ($op === 'update_status') {
        $id = (int)($_POST['id'] ?? 0);
        $newStatus = $_POST['status'] ?? '';
        $allowedStatuses = ['pending', 'approved', 'rejected'];

        if ($id && in_array($newStatus, $allowedStatuses, true)) {
            $s = db()->prepare("
                UPDATE users
                SET account_status = ?, status = ?
                WHERE id = ?
            ");
            $s->bind_param("ssi", $newStatus, $newStatus, $id);
            $s->execute();
            $s->close();

            flash('success', 'User status updated to ' . ucfirst($newStatus) . '.');
        } else {
            flash('danger', 'Invalid status update request.');
        }

        redirect(
            'users.php' .
            ($filter !== 'all' ? '?filter=' . urlencode($filter) : '')
        );
    }

    if ($op === 'delete') {
        try {
            $id = (int)$_POST['id'];

            $s = db()->prepare("DELETE FROM users WHERE id = ?");
            $s->bind_param("i", $id);
            $s->execute();
            $s->close();

            flash('success', 'User deleted successfully.');
        } catch (Throwable $e) {
            flash(
                'danger',
                'User cannot be deleted because they have active orders or linked records.'
            );
        }

        redirect(
            'users.php' .
            ($filter !== 'all' ? '?filter=' . urlencode($filter) : '')
        );
    }
}

$pageTitle = 'User Management';
include 'partials/header.php';
?>

<style>
.user-name-link {
    color: #111;
    text-decoration: none;
    cursor: pointer;
}
.user-name-link:hover {
    color: #4f46e5;
    text-decoration: underline;
}

.user-modal {
    display: none;
    position: fixed;
    z-index: 99999;
    inset: 0;
    background: rgba(15, 23, 42, .62);
    padding: 25px;
    overflow-y: auto;
}
.user-modal.show {
    display: flex;
    align-items: flex-start;
    justify-content: center;
}
.user-modal-box {
    width: min(1250px, 100%);
    margin: 10px auto;
    background: #fff;
    border-radius: 18px;
    box-shadow: 0 20px 60px rgba(0,0,0,.25);
    overflow: hidden;
}
.user-modal-header {
    padding: 18px 22px;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: sticky;
    top: 0;
    background: #fff;
    z-index: 2;
}
.user-modal-header h4 {
    margin: 0;
}
.user-modal-close {
    border: 0;
    background: transparent;
    font-size: 30px;
    line-height: 1;
    cursor: pointer;
    color: #64748b;
}
.user-modal-body {
    padding: 22px;
}

.user-summary-grid {
    display: grid;
    grid-template-columns: repeat(5, minmax(0, 1fr));
    gap: 12px;
    margin-bottom: 20px;
}
.user-summary-card {
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    padding: 14px;
    background: #f8fafc;
}
.user-summary-card small {
    display: block;
    color: #64748b;
    margin-bottom: 5px;
}
.user-summary-card strong {
    font-size: 18px;
}
.user-summary-card.balance-due strong {
    color: #dc2626;
}
.user-summary-card.balance-credit strong {
    color: #15803d;
}

.user-info-grid {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 12px;
    margin-bottom: 22px;
}
.user-info-card {
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    padding: 13px;
}
.user-info-card small {
    display: block;
    color: #64748b;
    margin-bottom: 4px;
}

.popup-section {
    border: 1px solid #e5e7eb;
    border-radius: 14px;
    margin-bottom: 18px;
    overflow: hidden;
}
.popup-section-title {
    padding: 13px 16px;
    background: #f8fafc;
    font-weight: 700;
    border-bottom: 1px solid #e5e7eb;
}

.popup-section-body {
    padding: 16px;
}

.order-box {
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    margin-bottom: 14px;
    overflow: hidden;
}
.order-header {
    padding: 12px 14px;
    background: #f8fafc;
    display: flex;
    justify-content: space-between;
    gap: 10px;
    align-items: center;
}
.order-items-table {
    margin: 0;
}
.order-items-table th {
    white-space: nowrap;
}

.popup-table {
    width: 100%;
    border-collapse: collapse;
}
.popup-table th,
.popup-table td {
    border-bottom: 1px solid #e5e7eb;
    padding: 9px 8px;
    vertical-align: middle;
}
.popup-table th {
    background: #f8fafc;
    font-size: 13px;
}
.popup-table tr:last-child td {
    border-bottom: 0;
}

.popup-form-grid {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 12px;
}
.popup-form-grid .full {
    grid-column: 1 / -1;
}
.popup-form-grid .half {
    grid-column: span 2;
}

.popup-form-label {
    font-size: 13px;
    font-weight: 600;
    margin-bottom: 5px;
}
.popup-form-grid input,
.popup-form-grid select,
.popup-form-grid textarea {
    width: 100%;
}

.return-total-box {
    font-size: 20px;
    font-weight: 700;
    background: #f8fafc;
}

.popup-message {
    display: none;
    padding: 10px 14px;
    border-radius: 8px;
    margin-bottom: 15px;
}
.popup-message.success {
    display: block;
    background: #dcfce7;
    color: #166534;
}
.popup-message.error {
    display: block;
    background: #fee2e2;
    color: #991b1b;
}

.popup-loading {
    text-align: center;
    padding: 40px;
    color: #64748b;
}

@media (max-width: 1000px) {
    .user-summary-grid,
    .user-info-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }

    .popup-form-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }
}

@media (max-width: 600px) {
    .user-modal {
        padding: 8px;
    }

    .user-summary-grid,
    .user-info-grid,
    .popup-form-grid {
        grid-template-columns: 1fr;
    }

    .popup-form-grid .half,
    .popup-form-grid .full {
        grid-column: auto;
    }

    .popup-table {
        min-width: 850px;
    }

    .popup-section-body {
        overflow-x: auto;
    }
}
</style>

<div class="card p-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h5 class="m-0">User Management</h5>

        <div class="btn-group btn-group-sm">
            <a href="users.php?filter=all"
               class="btn btn-<?= $filter === 'all' ? 'primary' : 'outline-primary' ?>">
                All
            </a>
            <a href="users.php?filter=pending"
               class="btn btn-<?= $filter === 'pending' ? 'warning' : 'outline-warning' ?>">
                Pending
            </a>
            <a href="users.php?filter=approved"
               class="btn btn-<?= $filter === 'approved' ? 'success' : 'outline-success' ?>">
                Approved
            </a>
            <a href="users.php?filter=rejected"
               class="btn btn-<?= $filter === 'rejected' ? 'danger' : 'outline-danger' ?>">
                Rejected
            </a>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table align-middle">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>User Details</th>
                    <th>Phone</th>
                    <th>Address</th>
                    <th>Registered</th>
                    <th>Status</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>

            <tbody>
                <?php
                if ($filter !== 'all') {
                    $s = db()->prepare("
                        SELECT *
                        FROM users
                        WHERE status = ?
                        ORDER BY id DESC
                    ");
                    $s->bind_param("s", $filter);
                    $s->execute();
                    $r = $s->get_result();
                    $s->close();
                } else {
                    $r = db()->query("SELECT * FROM users ORDER BY id DESC");
                }

                if ($r->num_rows === 0):
                ?>
                    <tr>
                        <td colspan="7" class="text-center text-muted py-4">
                            No users found for this filter.
                        </td>
                    </tr>
                <?php endif; ?>

                <?php while ($u = $r->fetch_assoc()):
                    $badgeClass = match($u['status']) {
                        'approved' => 'bg-success',
                        'rejected' => 'bg-danger',
                        default    => 'bg-warning text-dark'
                    };
                ?>
                    <tr>
                        <td>#<?= (int)$u['id'] ?></td>

                        <td>
                            <a href="#"
                               class="user-name-link"
                               onclick="openUserPopup(<?= (int)$u['id'] ?>); return false;">
                                <strong><?= e($u['full_name']) ?></strong>
                            </a>
                            <br>
                            <small class="text-muted"><?= e($u['email']) ?></small>
                        </td>

                        <td><?= e($u['phone']) ?></td>

                        <td>
                            <small><?= nl2br(e($u['address'])) ?></small>
                        </td>

                        <td>
                            <small>
                                <?= date('M d, Y h:i A', strtotime($u['created_at'])) ?>
                            </small>
                        </td>

                        <td>
                            <span class="badge <?= $badgeClass ?>">
                                <?= strtoupper(e($u['status'])) ?>
                            </span>
                        </td>

                        <td class="text-end">
                            <?php if ($u['status'] !== 'approved'): ?>
                                <form class="d-inline"
                                      method="post"
                                      action="users.php?filter=<?= e($filter) ?>">
                                    <input type="hidden" name="csrf" value="<?= e(csrf()) ?>">
                                    <input type="hidden" name="op" value="update_status">
                                    <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">
                                    <input type="hidden" name="status" value="approved">
                                    <button class="btn btn-sm btn-success"
                                            title="Approve User">
                                        Approve
                                    </button>
                                </form>
                            <?php endif; ?>

                            <?php if ($u['status'] !== 'rejected'): ?>
                                <form class="d-inline"
                                      method="post"
                                      action="users.php?filter=<?= e($filter) ?>">
                                    <input type="hidden" name="csrf" value="<?= e(csrf()) ?>">
                                    <input type="hidden" name="op" value="update_status">
                                    <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">
                                    <input type="hidden" name="status" value="rejected">
                                    <button class="btn btn-sm btn-outline-danger"
                                            data-confirm="Reject/Block this user?"
                                            title="Reject User">
                                        Reject
                                    </button>
                                </form>
                            <?php endif; ?>

                            <?php if ($u['status'] !== 'pending'): ?>
                                <form class="d-inline"
                                      method="post"
                                      action="users.php?filter=<?= e($filter) ?>">
                                    <input type="hidden" name="csrf" value="<?= e(csrf()) ?>">
                                    <input type="hidden" name="op" value="update_status">
                                    <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">
                                    <input type="hidden" name="status" value="pending">
                                    <button class="btn btn-sm btn-outline-warning"
                                            title="Set to Pending">
                                        Pending
                                    </button>
                                </form>
                            <?php endif; ?>

                            <form class="d-inline"
                                  method="post"
                                  action="users.php?filter=<?= e($filter) ?>">
                                <input type="hidden" name="csrf" value="<?= e(csrf()) ?>">
                                <input type="hidden" name="op" value="delete">
                                <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">
                                <button class="btn btn-sm btn-link text-danger p-0 ms-2"
                                        data-confirm="Permanently delete this user?"
                                        title="Delete">
                                    Delete
                                </button>
                            </form>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- USER DETAILS POPUP -->
<div id="userModal"
     class="user-modal"
     onclick="userModalBackgroundClick(event)">

    <div class="user-modal-box">
        <div class="user-modal-header">
            <h4 id="userModalTitle">User Details</h4>

            <button type="button"
                    class="user-modal-close"
                    onclick="closeUserPopup()">
                &times;
            </button>
        </div>

        <div class="user-modal-body">
            <div id="userPopupMessage" class="popup-message"></div>

            <div id="userModalContent">
                <div class="popup-loading">
                    Loading user details...
                </div>
            </div>
        </div>
    </div>
</div>

<script>
const userPopupCsrf = <?= json_encode(csrf()) ?>;
let currentUserId = 0;
let currentUserData = null;

function money(value) {
    return 'Rs. ' + Number(value || 0).toLocaleString('en-LK', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}

function esc(value) {
    const div = document.createElement('div');
    div.textContent = value == null ? '' : String(value);
    return div.innerHTML;
}

function showPopupMessage(text, type = 'success') {
    const box = document.getElementById('userPopupMessage');

    box.className = 'popup-message ' + type;
    box.textContent = text;
    box.style.display = 'block';

    setTimeout(() => {
        box.style.display = 'none';
    }, 4000);
}

function openUserPopup(userId) {
    currentUserId = Number(userId);

    document.getElementById('userModal').classList.add('show');

    document.getElementById('userModalTitle').textContent =
        'User Details';

    document.getElementById('userModalContent').innerHTML =
        '<div class="popup-loading">Loading user details...</div>';

    loadUserDetails();
}

function closeUserPopup() {
    document.getElementById('userModal').classList.remove('show');
    currentUserId = 0;
    currentUserData = null;
}

function userModalBackgroundClick(event) {
    if (event.target.id === 'userModal') {
        closeUserPopup();
    }
}

async function loadUserDetails() {
    try {
        const url =
            'users.php?ajax=user_details&user_id=' +
            encodeURIComponent(currentUserId);

        const response = await fetch(url, {
            cache: 'no-store',
            credentials: 'same-origin'
        });

        const data = await response.json();

        if (!data.success) {
            throw new Error(data.message || 'Unable to load user.');
        }

        currentUserData = data;
        renderUserPopup(data);

    } catch (error) {
        document.getElementById('userModalContent').innerHTML =
            '<div class="popup-message error" style="display:block">' +
            esc(error.message) +
            '</div>';
    }
}

function renderUserPopup(data) {
    const u = data.user;
    const s = data.summary;

    document.getElementById('userModalTitle').textContent =
        u.full_name + ' (#' + u.id + ')';

    const balanceClass =
        Number(s.balance) > 0
            ? 'balance-due'
            : 'balance-credit';

    const balanceText =
        Number(s.balance) > 0
            ? money(s.balance) + ' Due'
            : Number(s.balance) < 0
                ? money(Math.abs(s.balance)) + ' Credit'
                : 'PAID';

    let html = `
        <div class="user-info-grid">
            <div class="user-info-card">
                <small>Full Name</small>
                <strong>${esc(u.full_name)}</strong>
            </div>

            <div class="user-info-card">
                <small>Phone</small>
                <strong>${esc(u.phone)}</strong>
            </div>

            <div class="user-info-card">
                <small>Email</small>
                <strong>${esc(u.email)}</strong>
            </div>

            <div class="user-info-card">
                <small>Address</small>
                <strong>${esc(u.address).replace(/\n/g, '<br>')}</strong>
            </div>
        </div>

        <div class="user-summary-grid">
            <div class="user-summary-card">
                <small>Total Orders</small>
                <strong>${data.orders.length}</strong>
            </div>

            <div class="user-summary-card">
                <small>Gross Order Total</small>
                <strong>${money(s.gross_total)}</strong>
            </div>

            <div class="user-summary-card">
                <small>Returned Amount</small>
                <strong>${money(s.returned_total)}</strong>
            </div>

            <div class="user-summary-card">
                <small>Received So Far</small>
                <strong>${money(s.received_total)}</strong>
            </div>

            <div class="user-summary-card ${balanceClass}">
                <small>Current Balance</small>
                <strong>${balanceText}</strong>
            </div>
        </div>
    `;

    /* Orders */
    html += `
        <div class="popup-section">
            <div class="popup-section-title">
                Order Details
            </div>

            <div class="popup-section-body">
    `;

    if (!data.orders.length) {
        html += '<div class="text-muted">No orders found for this user.</div>';
    }

    data.orders.forEach(order => {
        html += `
            <div class="order-box">
                <div class="order-header">
                    <div>
                        <strong>Order #${order.id}</strong>
                        <small class="text-muted ms-2">
                            ${esc(formatDate(order.created_at))}
                        </small>
                    </div>

                    <div>
                        <span class="badge bg-secondary">
                            ${esc(order.status)}
                        </span>

                        <strong class="ms-3">
                            ${money(order.total_amount)}
                        </strong>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table order-items-table align-middle">
                        <thead>
                            <tr>
                                <th>Item</th>
                                <th>Qty</th>
                                <th>Delivered</th>
                                <th>Returned</th>
                                <th>Unit Price</th>
                                <th>Subtotal</th>
                                <th>Return</th>
                            </tr>
                        </thead>
                        <tbody>
        `;

        if (!order.items.length) {
            html += `
                <tr>
                    <td colspan="7" class="text-muted text-center">
                        No items
                    </td>
                </tr>
            `;
        }

        order.items.forEach(item => {
            html += `
                <tr>
                    <td>
                        ${esc(item.description)}
                    </td>

                    <td>${item.quantity}</td>

                    <td>${item.quantity_delivered}</td>

                    <td>
                        ${item.returned_quantity}
                        ${item.returned_amount > 0
                            ? '<br><small class="text-danger">' +
                              money(item.returned_amount) +
                              '</small>'
                            : ''}
                    </td>

                    <td>${money(item.unit_price)}</td>

                    <td>${money(item.subtotal)}</td>

                    <td>
                        ${
                            Number(item.available_return_qty) > 0
                                ? `<button type="button"
                                           class="btn btn-sm btn-outline-danger"
                                           onclick="selectReturn(${order.id}, ${item.id})">
                                       Return
                                   </button>`
                                : '<span class="text-muted">No return</span>'
                        }
                    </td>
                </tr>
            `;
        });

        html += `
                        </tbody>
                    </table>
                </div>
            </div>
        `;
    });

    html += `
            </div>
        </div>
    `;

    /* Payment section */
    html += `
        <div class="popup-section">
            <div class="popup-section-title">
                Add Received Amount
            </div>

            <div class="popup-section-body">
                <form onsubmit="addPayment(event)">
                    <div class="popup-form-grid">

                        <div>
                            <div class="popup-form-label">Order</div>
                            <select id="payment_order_id" class="form-select">
                                <option value="0">General / Customer Account</option>
                                ${data.orders.map(o =>
                                    `<option value="${o.id}">
                                        Order #${o.id} - ${money(o.total_amount)}
                                    </option>`
                                ).join('')}
                            </select>
                        </div>

                        <div>
                            <div class="popup-form-label">Received Amount</div>
                            <input id="payment_amount"
                                   type="number"
                                   step="0.01"
                                   min="0.01"
                                   class="form-control"
                                   required>
                        </div>

                        <div>
                            <div class="popup-form-label">Payment Method</div>
                            <select id="payment_method" class="form-select">
                                <option>Cash</option>
                                <option>Bank Transfer</option>
                                <option>Card</option>
                                <option>Cheque</option>
                                <option>Other</option>
                            </select>
                        </div>

                        <div>
                            <div class="popup-form-label">Payment Date</div>
                            <input id="payment_date"
                                   type="datetime-local"
                                   class="form-control"
                                   value="${currentDateTimeLocal()}">
                        </div>

                        <div>
                            <div class="popup-form-label">Reference No</div>
                            <input id="payment_reference"
                                   type="text"
                                   class="form-control">
                        </div>

                        <div class="half">
                            <div class="popup-form-label">Notes</div>
                            <input id="payment_notes"
                                   type="text"
                                   class="form-control">
                        </div>

                        <div class="d-flex align-items-end">
                            <button class="btn btn-success w-100">
                                + Add Received Amount
                            </button>
                        </div>

                    </div>
                </form>
            </div>
        </div>
    `;

    /* Payment history */
    html += `
        <div class="popup-section">
            <div class="popup-section-title">
                Payment History
            </div>

            <div class="popup-section-body">
                <div class="table-responsive">
                    <table class="popup-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Order</th>
                                <th>Method</th>
                                <th>Reference</th>
                                <th class="text-end">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
    `;

    if (!data.payments.length) {
        html += `
            <tr>
                <td colspan="5" class="text-center text-muted">
                    No payments recorded.
                </td>
            </tr>
        `;
    }

    data.payments.forEach(payment => {
        html += `
            <tr>
                <td>${esc(formatDate(payment.payment_date))}</td>
                <td>
                    ${payment.order_id
                        ? 'Order #' + payment.order_id
                        : 'General'}
                </td>
                <td>${esc(payment.payment_method)}</td>
                <td>${esc(payment.reference_no)}</td>
                <td class="text-end">
                    <strong>${money(payment.amount)}</strong>
                </td>
            </tr>
        `;
    });

    html += `
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;

    /* Warranty */
    html += `
        <div class="popup-section">
            <div class="popup-section-title">
                Add Warranty
            </div>

            <div class="popup-section-body">
                <form onsubmit="addWarranty(event)">
                    <div class="popup-form-grid">

                        <div>
                            <div class="popup-form-label">Order</div>
                            <select id="warranty_order_id"
                                    class="form-select"
                                    onchange="loadWarrantyItems()">
                                <option value="0">General Warranty</option>
                                ${data.orders.map(o =>
                                    `<option value="${o.id}">
                                        Order #${o.id}
                                    </option>`
                                ).join('')}
                            </select>
                        </div>

                        <div>
                            <div class="popup-form-label">Item</div>
                            <select id="warranty_item_id"
                                    class="form-select">
                                <option value="0">General Warranty</option>
                            </select>
                        </div>

                        <div>
                            <div class="popup-form-label">Warranty Title</div>
                            <input id="warranty_title"
                                   type="text"
                                   class="form-control"
                                   value="Standard Warranty"
                                   required>
                        </div>

                        <div>
                            <div class="popup-form-label">Start Date</div>
                            <input id="warranty_start"
                                   type="date"
                                   class="form-control"
                                   required>
                        </div>

                        <div>
                            <div class="popup-form-label">End Date</div>
                            <input id="warranty_end"
                                   type="date"
                                   class="form-control"
                                   required>
                        </div>

                        <div class="half">
                            <div class="popup-form-label">Notes</div>
                            <input id="warranty_notes"
                                   type="text"
                                   class="form-control">
                        </div>

                        <div class="d-flex align-items-end">
                            <button class="btn btn-primary w-100">
                                + Add Warranty
                            </button>
                        </div>

                    </div>
                </form>
            </div>
        </div>
    `;

    /* Warranty history */
    html += `
        <div class="popup-section">
            <div class="popup-section-title">
                Warranty History
            </div>

            <div class="popup-section-body">
                <div class="table-responsive">
                    <table class="popup-table">
                        <thead>
                            <tr>
                                <th>Item</th>
                                <th>Warranty</th>
                                <th>Start</th>
                                <th>End</th>
                                <th>Status</th>
                                <th>Notes</th>
                            </tr>
                        </thead>
                        <tbody>
    `;

    if (!data.warranties.length) {
        html += `
            <tr>
                <td colspan="6" class="text-center text-muted">
                    No warranties recorded.
                </td>
            </tr>
        `;
    }

    data.warranties.forEach(w => {
        const description =
            (w.product_brand + ' ' + w.display_model).trim() ||
            'General Warranty';

        html += `
            <tr>
                <td>${esc(description)}</td>
                <td>${esc(w.warranty_title)}</td>
                <td>${esc(w.warranty_start)}</td>
                <td>${esc(w.warranty_end)}</td>
                <td>${esc(w.warranty_status)}</td>
                <td>${esc(w.notes)}</td>
            </tr>
        `;
    });

    html += `
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;

    /* Return form */
    html += `
        <div class="popup-section">
            <div class="popup-section-title">
                Return an Item
            </div>

            <div class="popup-section-body">
                <form onsubmit="addReturn(event)">
                    <div class="popup-form-grid">

                        <div>
                            <div class="popup-form-label">Order</div>
                            <select id="return_order_id"
                                    class="form-select"
                                    onchange="loadReturnItems()">
                                <option value="">Select order</option>
                                ${data.orders.map(o =>
                                    `<option value="${o.id}">
                                        Order #${o.id}
                                    </option>`
                                ).join('')}
                            </select>
                        </div>

                        <div class="half">
                            <div class="popup-form-label">Item</div>
                            <select id="return_item_id"
                                    class="form-select"
                                    onchange="updateReturnPrice()">
                                <option value="">Select item</option>
                            </select>
                        </div>

                        <div>
                            <div class="popup-form-label">Quantity</div>
                            <input id="return_quantity"
                                   type="number"
                                   min="1"
                                   value="1"
                                   class="form-control"
                                   oninput="updateReturnTotal()"
                                   required>
                        </div>

                        <div>
                            <div class="popup-form-label">Unit Price</div>
                            <input id="return_unit_price"
                                   class="form-control"
                                   value="Rs. 0.00"
                                   readonly>
                        </div>

                        <div>
                            <div class="popup-form-label">Total Return Amount</div>
                            <input id="return_total"
                                   class="form-control return-total-box"
                                   value="Rs. 0.00"
                                   readonly>
                        </div>

                        <div>
                            <div class="popup-form-label">Reason</div>
                            <input id="return_reason"
                                   type="text"
                                   class="form-control"
                                   placeholder="Reason for return">
                        </div>

                        <div class="half">
                            <div class="popup-form-label">Notes</div>
                            <input id="return_notes"
                                   type="text"
                                   class="form-control">
                        </div>

                        <div class="d-flex align-items-end">
                            <button class="btn btn-danger w-100">
                                Record Return
                            </button>
                        </div>

                    </div>
                </form>
            </div>
        </div>
    `;

    /* Return history */
    html += `
        <div class="popup-section">
            <div class="popup-section-title">
                Return History
            </div>

            <div class="popup-section-body">
                <div class="table-responsive">
                    <table class="popup-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Order</th>
                                <th>Item</th>
                                <th>Qty</th>
                                <th>Unit Price</th>
                                <th class="text-end">Total</th>
                                <th>Reason</th>
                            </tr>
                        </thead>
                        <tbody>
    `;

    if (!data.returns.length) {
        html += `
            <tr>
                <td colspan="7" class="text-center text-muted">
                    No returns recorded.
                </td>
            </tr>
        `;
    }

    data.returns.forEach(r => {
        html += `
            <tr>
                <td>${esc(formatDate(r.return_date))}</td>
                <td>Order #${r.order_id}</td>
                <td>${esc(
                    (r.product_brand + ' ' + r.display_model).trim()
                )}</td>
                <td>${r.quantity}</td>
                <td>${money(r.unit_price)}</td>
                <td class="text-end">
                    <strong class="text-danger">
                        ${money(r.total_amount)}
                    </strong>
                </td>
                <td>${esc(r.reason)}</td>
            </tr>
        `;
    });

    html += `
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;

    document.getElementById('userModalContent').innerHTML = html;

    /* Default warranty dates */
    const today = new Date();
    const todayString = today.toISOString().slice(0, 10);

    const end = new Date(today);
    end.setFullYear(end.getFullYear() + 1);
    const endString = end.toISOString().slice(0, 10);

    document.getElementById('warranty_start').value = todayString;
    document.getElementById('warranty_end').value = endString;
}

function formatDate(value) {
    if (!value) return '';

    const date = new Date(String(value).replace(' ', 'T'));

    if (Number.isNaN(date.getTime())) {
        return String(value);
    }

    return date.toLocaleString('en-LK', {
        year: 'numeric',
        month: 'short',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function currentDateTimeLocal() {
    const d = new Date();

    const pad = n => String(n).padStart(2, '0');

    return d.getFullYear() + '-' +
        pad(d.getMonth() + 1) + '-' +
        pad(d.getDate()) + 'T' +
        pad(d.getHours()) + ':' +
        pad(d.getMinutes());
}

function loadReturnItems() {
    const orderId = Number(
        document.getElementById('return_order_id').value
    );

    const select = document.getElementById('return_item_id');

    select.innerHTML = '<option value="">Select item</option>';

    if (!orderId || !currentUserData) {
        updateReturnPrice();
        return;
    }

    const order = currentUserData.orders.find(
        o => Number(o.id) === orderId
    );

    if (!order) {
        updateReturnPrice();
        return;
    }

    order.items.forEach(item => {
        if (Number(item.available_return_qty) > 0) {
            const option = document.createElement('option');

            option.value = item.id;
            option.dataset.price = item.unit_price;
            option.dataset.available = item.available_return_qty;

            option.textContent =
                item.description +
                ' | Delivered: ' + (Number(item.quantity_delivered) > 0
                    ? item.quantity_delivered
                    : item.quantity) +
                ' | Available: ' + item.available_return_qty +
                ' | ' + money(item.unit_price);

            select.appendChild(option);
        }
    });

    updateReturnPrice();
}

function selectReturn(orderId, itemId) {
    document.getElementById('return_order_id').value = orderId;
    loadReturnItems();

    const select = document.getElementById('return_item_id');
    select.value = itemId;

    updateReturnPrice();

    document.getElementById('return_quantity').focus();

    document.getElementById('return_order_id')
        .scrollIntoView({ behavior: 'smooth', block: 'center' });
}

function updateReturnPrice() {
    const select = document.getElementById('return_item_id');
    const option = select.options[select.selectedIndex];

    const price = option && option.dataset.price
        ? Number(option.dataset.price)
        : 0;

    const quantityInput =
        document.getElementById('return_quantity');

    if (option && option.dataset.available) {
        quantityInput.max = option.dataset.available;

        if (
            Number(quantityInput.value) >
            Number(option.dataset.available)
        ) {
            quantityInput.value = option.dataset.available;
        }
    } else {
        quantityInput.removeAttribute('max');
    }

    document.getElementById('return_unit_price').value =
        money(price);

    updateReturnTotal();
}

function updateReturnTotal() {
    const select = document.getElementById('return_item_id');
    const option = select.options[select.selectedIndex];

    const price = option && option.dataset.price
        ? Number(option.dataset.price)
        : 0;

    const qty = Number(
        document.getElementById('return_quantity').value || 0
    );

    document.getElementById('return_total').value =
        money(price * qty);
}

function loadWarrantyItems() {
    const orderId = Number(
        document.getElementById('warranty_order_id').value
    );

    const select =
        document.getElementById('warranty_item_id');

    select.innerHTML =
        '<option value="0">General Warranty</option>';

    if (!orderId || !currentUserData) {
        return;
    }

    const order = currentUserData.orders.find(
        o => Number(o.id) === orderId
    );

    if (!order) return;

    order.items.forEach(item => {
        const option = document.createElement('option');

        option.value = item.id;
        option.textContent = item.description;

        select.appendChild(option);
    });
}

async function postUserAction(action, fields) {
    const body = new URLSearchParams();

    body.append('ajax_action', action);
    body.append('user_id', currentUserId);
    body.append('csrf', userPopupCsrf);

    Object.keys(fields).forEach(key => {
        body.append(key, fields[key] ?? '');
    });

    const response = await fetch('users.php', {
        method: 'POST',
        headers: {
            'Content-Type':
                'application/x-www-form-urlencoded'
        },
        credentials: 'same-origin',
        body
    });

    const data = await response.json();

    if (!data.success) {
        throw new Error(
            data.message || 'Operation failed.'
        );
    }

    return data;
}

async function addPayment(event) {
    event.preventDefault();

    try {
        const amount = Number(
            document.getElementById('payment_amount').value
        );

        if (amount <= 0) {
            throw new Error(
                'Enter a valid received amount.'
            );
        }

        await postUserAction('add_payment', {
            amount: amount,
            order_id:
                document.getElementById('payment_order_id').value,
            payment_date:
                document.getElementById('payment_date').value,
            payment_method:
                document.getElementById('payment_method').value,
            reference_no:
                document.getElementById('payment_reference').value,
            notes:
                document.getElementById('payment_notes').value
        });

        showPopupMessage(
            'Received amount added successfully.'
        );

        await loadUserDetails();

    } catch (error) {
        showPopupMessage(error.message, 'error');
    }
}

async function addWarranty(event) {
    event.preventDefault();

    try {
        await postUserAction('add_warranty', {
            order_id:
                document.getElementById('warranty_order_id').value,
            order_item_id:
                document.getElementById('warranty_item_id').value,
            warranty_title:
                document.getElementById('warranty_title').value,
            warranty_start:
                document.getElementById('warranty_start').value,
            warranty_end:
                document.getElementById('warranty_end').value,
            notes:
                document.getElementById('warranty_notes').value
        });

        showPopupMessage(
            'Warranty added successfully.'
        );

        await loadUserDetails();

    } catch (error) {
        showPopupMessage(error.message, 'error');
    }
}

async function addReturn(event) {
    event.preventDefault();

    try {
        const orderId = Number(
            document.getElementById('return_order_id').value
        );
        const itemId = Number(
            document.getElementById('return_item_id').value
        );
        const quantity = Number(
            document.getElementById('return_quantity').value
        );

        if (!orderId || !itemId || quantity <= 0) {
            throw new Error(
                'Select an order, item and valid quantity.'
            );
        }

        const option =
            document.getElementById('return_item_id')
                .options[
                    document.getElementById('return_item_id')
                        .selectedIndex
                ];

        const available = Number(
            option.dataset.available || 0
        );

        if (quantity > available) {
            throw new Error(
                'Return quantity cannot exceed the available return quantity.'
            );
        }

        const price = Number(
            option.dataset.price || 0
        );

        const confirmed = confirm(
            'Record return of ' +
            quantity +
            ' item(s) for ' +
            money(price * quantity) +
            '?'
        );

        if (!confirmed) return;

        await postUserAction('add_return', {
            order_id: orderId,
            order_item_id: itemId,
            quantity: quantity,
            reason:
                document.getElementById('return_reason').value,
            notes:
                document.getElementById('return_notes').value
        });

        showPopupMessage(
            'Return recorded. Stock has also been updated.'
        );

        await loadUserDetails();

    } catch (error) {
        showPopupMessage(error.message, 'error');
    }
}

document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape' && currentUserId) {
        closeUserPopup();
    }
});
</script>

<?php include 'partials/footer.php'; ?>
