<?php
require_once 'db.php';
requireAdmin();

$message = '';
$error = '';

function makeCode($text)
{
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9]+/', '_', $text);
    $text = trim($text, '_');

    return $text !== '' ? $text : 'payment_type';
}

/*
|--------------------------------------------------------------------------
| Add Payment Type
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_payment_type'])) {
    $label = trim($_POST['label'] ?? '');
    $code = trim($_POST['code'] ?? '');
    $fee = (int)($_POST['fee'] ?? 0);
    $is_manual_fee = isset($_POST['is_manual_fee']) ? 1 : 0;
    $status = trim($_POST['status'] ?? 'active');
    $sort_order = (int)($_POST['sort_order'] ?? 0);

    if ($label === '') {
        $error = 'Label is required.';
    } else {
        if ($code === '') {
            $code = makeCode($label);
        } else {
            $code = makeCode($code);
        }

        if (!in_array($status, ['active', 'inactive'], true)) {
            $status = 'active';
        }

        try {
            $checkStmt = $pdo->prepare("SELECT id FROM payment_types WHERE code = ? LIMIT 1");
            $checkStmt->execute([$code]);

            if ($checkStmt->fetch()) {
                $error = 'Code already exists. Please use another code.';
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO payment_types (code, label, fee, is_manual_fee, status, sort_order)
                    VALUES (?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $code,
                    $label,
                    $fee,
                    $is_manual_fee,
                    $status,
                    $sort_order
                ]);

                $message = 'Payment type added successfully.';
            }
        } catch (Throwable $e) {
            $error = 'Error adding payment type: ' . $e->getMessage();
        }
    }
}

/*
|--------------------------------------------------------------------------
| Update Payment Type
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_payment_type'])) {
    $id = (int)($_POST['id'] ?? 0);
    $label = trim($_POST['label'] ?? '');
    $code = trim($_POST['code'] ?? '');
    $fee = (int)($_POST['fee'] ?? 0);
    $is_manual_fee = isset($_POST['is_manual_fee']) ? 1 : 0;
    $status = trim($_POST['status'] ?? 'active');
    $sort_order = (int)($_POST['sort_order'] ?? 0);

    if ($id <= 0) {
        $error = 'Invalid payment type ID.';
    } elseif ($label === '') {
        $error = 'Label is required.';
    } else {
        $code = makeCode($code !== '' ? $code : $label);

        if (!in_array($status, ['active', 'inactive'], true)) {
            $status = 'active';
        }

        try {
            $checkStmt = $pdo->prepare("SELECT id FROM payment_types WHERE code = ? AND id != ? LIMIT 1");
            $checkStmt->execute([$code, $id]);

            if ($checkStmt->fetch()) {
                $error = 'Code already exists. Please use another code.';
            } else {
                $stmt = $pdo->prepare("
                    UPDATE payment_types
                    SET code = ?, label = ?, fee = ?, is_manual_fee = ?, status = ?, sort_order = ?
                    WHERE id = ?
                ");
                $stmt->execute([
                    $code,
                    $label,
                    $fee,
                    $is_manual_fee,
                    $status,
                    $sort_order,
                    $id
                ]);

                $message = 'Payment type updated successfully.';
            }
        } catch (Throwable $e) {
            $error = 'Error updating payment type: ' . $e->getMessage();
        }
    }
}

/*
|--------------------------------------------------------------------------
| Delete Payment Type
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_payment_type'])) {
    $id = (int)($_POST['id'] ?? 0);

    if ($id <= 0) {
        $error = 'Invalid payment type ID.';
    } else {
        try {
            $stmt = $pdo->prepare("DELETE FROM payment_types WHERE id = ?");
            $stmt->execute([$id]);
            $message = 'Payment type deleted successfully.';
        } catch (Throwable $e) {
            $error = 'Error deleting payment type: ' . $e->getMessage();
        }
    }
}

/*
|--------------------------------------------------------------------------
| Load Payment Types
|--------------------------------------------------------------------------
*/
$paymentTypes = $pdo->query("
    SELECT *
    FROM payment_types
    ORDER BY sort_order ASC, id ASC
")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Payment Types</title>
    <link rel="stylesheet" href="css/style.css?v=1">

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f3f6fb;
            color: #111827;
        }

        .page-topbar {
            margin: 20px 0;
            padding: 0 16px;
        }

        .page-back-btn {
            display: inline-block;
            background: #2563eb;
            color: #fff;
            padding: 8px 14px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: bold;
        }

        .page-back-btn:hover {
            background: #1d4ed8;
        }

        .payment-type-container {
            max-width: 1150px;
            margin: 24px auto;
            padding: 0 16px;
        }

        .payment-type-box {
            background: #fff;
            border-radius: 16px;
            padding: 24px;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.05);
            margin-bottom: 20px;
        }

        .payment-type-title,
        .payment-type-box h2 {
            margin-top: 0;
        }

        .payment-type-title {
            font-size: 28px;
            margin-bottom: 16px;
        }

        .message {
            background: #dcfce7;
            color: #166534;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 14px;
        }

        .error {
            background: #fee2e2;
            color: #991b1b;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 14px;
        }

        .payment-type-grid {
            display: grid;
            grid-template-columns: 2fr 2fr 1fr 1fr 1fr 1fr auto;
            gap: 12px;
            align-items: end;
        }

        .payment-type-field label {
            font-weight: bold;
            display: block;
            margin-bottom: 6px;
            font-size: 14px;
        }

        .payment-type-field input,
        .payment-type-field select {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #d1d5db;
            border-radius: 10px;
            font-size: 14px;
            background: #fff;
        }

        .payment-type-checkbox-wrap {
            display: flex;
            align-items: center;
            gap: 8px;
            padding-top: 30px;
        }

        .payment-type-checkbox-wrap input[type="checkbox"] {
            width: auto;
            margin: 0;
        }

        .payment-type-btn {
            padding: 10px 14px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-weight: bold;
        }

        .payment-type-btn-primary {
            background: #2563eb;
            color: white;
        }

        .payment-type-btn-primary:hover {
            background: #1d4ed8;
        }

        .payment-type-btn-danger {
            background: #dc2626;
            color: white;
        }

        .payment-type-btn-danger:hover {
            background: #b91c1c;
        }

        .payment-type-btn-secondary {
            background: #e5e7eb;
            color: #111827;
        }

        .payment-type-table-wrap {
            width: 100%;
            overflow-x: auto;
        }

        .payment-type-table {
            width: 100%;
            border-collapse: collapse;
        }

        .payment-type-table th,
        .payment-type-table td {
            text-align: left;
            padding: 12px 10px;
            border-bottom: 1px solid #e5e7eb;
            vertical-align: middle;
            font-size: 14px;
        }

        .payment-type-table th {
            background: #f8fafc;
        }

        .payment-type-status-active {
            color: #166534;
            font-weight: bold;
        }

        .payment-type-status-inactive {
            color: #991b1b;
            font-weight: bold;
        }

        .payment-type-inline-form {
            display: contents;
        }

        .payment-type-actions {
            display: flex;
            gap: 8px;
        }

        .payment-type-small {
            font-size: 12px;
            color: #6b7280;
        }

        input[type="number"]::-webkit-outer-spin-button,
        input[type="number"]::-webkit-inner-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }

        input[type="number"] {
            -moz-appearance: textfield;
            appearance: textfield;
        }

        @media (max-width: 900px) {
            .payment-type-grid {
                grid-template-columns: 1fr;
            }

            .payment-type-table,
            .payment-type-table thead,
            .payment-type-table tbody,
            .payment-type-table th,
            .payment-type-table td,
            .payment-type-table tr {
                display: block;
            }

            .payment-type-table thead {
                display: none;
            }

            .payment-type-table tr {
                margin-bottom: 16px;
                border: 1px solid #e5e7eb;
                border-radius: 12px;
                padding: 12px;
                background: #fff;
            }

            .payment-type-table td {
                border: none;
                padding: 8px 0;
            }

            .payment-type-inline-form {
                display: block;
            }

            .payment-type-actions {
                margin-top: 10px;
            }
        }
    </style>
</head>
<body>
    <?php include 'header.php'; ?>

    <div class="page-topbar">
        <a href="admin-dashboard.php" class="page-back-btn">← Dashboard</a>
    </div>

    <div class="payment-type-container">

        <div class="payment-type-box">
            <h1 class="payment-type-title">Manage Payment Types</h1>

            <?php if ($message): ?>
                <div class="message"><?= esc($message) ?></div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="error"><?= esc($error) ?></div>
            <?php endif; ?>

            <h2>Add New Payment Type</h2>

            <form method="POST">
                <input type="hidden" name="add_payment_type" value="1">

                <div class="payment-type-grid">
                    <div class="payment-type-field">
                        <label>Label *</label>
                        <input type="text" name="label" placeholder="Setup new machine" required>
                    </div>

                    <div class="payment-type-field">
                        <label>Code</label>
                        <input type="text" name="code" placeholder="setup_new_machine">
                    </div>

                    <div class="payment-type-field">
                        <label>Fee</label>
                        <input type="number" step="1" min="0" name="fee" value="0">
                    </div>

                    <div class="payment-type-field">
                        <label>Status</label>
                        <select name="status">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>

                    <div class="payment-type-field">
                        <label>Sort Order</label>
                        <input type="number" step="1" name="sort_order" value="0">
                    </div>

                    <div class="payment-type-checkbox-wrap">
                        <input type="checkbox" name="is_manual_fee" id="is_manual_fee_add">
                        <label for="is_manual_fee_add" style="margin:0;">Manual Fee</label>
                    </div>

                    <div>
                        <button type="submit" class="payment-type-btn payment-type-btn-primary">Add</button>
                    </div>
                </div>

                <p class="payment-type-small" style="margin-top:12px;">
                    Example: Label = Setup new machine, Code = setup_new_machine, Fee = 20000
                </p>
            </form>
        </div>

        <div class="payment-type-box">
            <h2>Existing Payment Types</h2>

            <?php if ($paymentTypes): ?>
                <div class="payment-type-table-wrap">
                    <table class="payment-type-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Label</th>
                                <th>Code</th>
                                <th>Fee</th>
                                <th>Manual Fee</th>
                                <th>Status</th>
                                <th>Sort Order</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($paymentTypes as $row): ?>
                                <tr>
                                    <form method="POST" class="payment-type-inline-form">
                                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">

                                        <td><?= (int)$row['id'] ?></td>

                                        <td>
                                            <input type="text" name="label" value="<?= esc($row['label']) ?>" required>
                                        </td>

                                        <td>
                                            <input type="text" name="code" value="<?= esc($row['code']) ?>" required>
                                        </td>

                                        <td>
                                            <input type="number" step="1" min="0" name="fee" value="<?= (int)$row['fee'] ?>">
                                        </td>

                                        <td>
                                            <input type="checkbox" name="is_manual_fee" value="1" <?= !empty($row['is_manual_fee']) ? 'checked' : '' ?>>
                                        </td>

                                        <td>
                                            <select name="status">
                                                <option value="active" <?= $row['status'] === 'active' ? 'selected' : '' ?>>Active</option>
                                                <option value="inactive" <?= $row['status'] === 'inactive' ? 'selected' : '' ?>>Inactive</option>
                                            </select>
                                        </td>

                                        <td>
                                            <input type="number" step="1" name="sort_order" value="<?= (int)$row['sort_order'] ?>">
                                        </td>

                                        <td>
                                            <div class="payment-type-actions">
                                                <button type="submit" name="update_payment_type" value="1" class="payment-type-btn payment-type-btn-primary">Save</button>
                                                <button type="submit" name="delete_payment_type" value="1" class="payment-type-btn payment-type-btn-danger" onclick="return confirm('Delete this payment type?')">Delete</button>
                                            </div>
                                        </td>
                                    </form>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <p>No payment types found.</p>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>