<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require '../config.php';
// Hapus pengecekan session dan redirect login agar admin bisa akses tanpa login
require 'sidebar.php';

// --- PHP Logic Enhancements ---

// Handle success/error messages
$message = '';
$message_type = '';

if (isset($_GET['success'])) {
    $message = 'Status pesanan berhasil diupdate!';
    $message_type = 'success';
} elseif (isset($_GET['error'])) {
    switch ($_GET['error']) {
        case 'status_invalid':
            $message = 'Status yang dipilih tidak valid.';
            $message_type = 'danger';
            break;
        case 'resi_kosong':
            $message = 'Nomor resi harus diisi untuk status "Dikirim".';
            $message_type = 'warning';
            break;
        default:
            $message = 'Terjadi kesalahan saat mengupdate status.';
            $message_type = 'danger';
    }
}

// Get status from filter (if any)
$status_filter = $_GET['status'] ?? '';

// Validate and sanitize status filter
$valid_statuses = ['menunggu', 'dibayar', 'dikirim', 'selesai', 'dibatalkan']; // Add 'dibatalkan' to valid statuses
if (!in_array($status_filter, $valid_statuses)) {
    $status_filter = ''; // Reset to empty if invalid
}

// Prepare the base query
$sql_query = "SELECT t.*, u.nama AS nama_pelanggan
              FROM transaksi t
              JOIN pengguna u ON t.pengguna_id = u.id";

$where_clauses = [];
$params = [];
$types = '';

// Add status filter if set
if ($status_filter) {
    $where_clauses[] = "t.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

// Construct the full query with WHERE clause
if (!empty($where_clauses)) {
    $sql_query .= " WHERE " . implode(" AND ", $where_clauses);
}

// Add ordering
$sql_query .= " ORDER BY t.dibuat_pada DESC";

// Prepare and execute the statement
$stmt = $conn->prepare($sql_query);
if ($stmt === false) {
    die("Prepare failed: " . $conn->error);
}

if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$transaksi = $stmt->get_result();

// --- Alert Handling ---
// Re-implementing the robust $_SESSION['alert'] system
// This replaces the $_GET['success'] and $_GET['error'] checks
$alert_message = '';
$alert_type = '';

if (isset($_SESSION['alert'])) {
    $alert_type = $_SESSION['alert']['type'];
    $alert_message = $_SESSION['alert']['message'];
    unset($_SESSION['alert']); // Clear the alert after displaying
}

// Handle URL parameters for success/error messages
if (isset($_GET['success'])) {
    $alert_message = 'Status pesanan berhasil diupdate!';
    $alert_type = 'success';
} elseif (isset($_GET['error'])) {
    switch ($_GET['error']) {
        case 'status_invalid':
            $alert_message = 'Status yang dipilih tidak valid.';
            $alert_type = 'danger';
            break;
        case 'resi_kosong':
            $alert_message = 'Nomor resi harus diisi untuk status "Dikirim".';
            $alert_type = 'warning';
            break;
        case 'missing_data':
            $alert_message = 'Data yang dikirim tidak lengkap.';
            $alert_type = 'danger';
            break;
        case 'invalid_id':
            $alert_message = 'ID transaksi tidak valid.';
            $alert_type = 'danger';
            break;
        case 'transaksi_not_found':
            $alert_message = 'Transaksi tidak ditemukan.';
            $alert_type = 'danger';
            break;
        case 'update_failed':
            $alert_message = 'Gagal mengupdate status pesanan. Silakan coba lagi.';
            $alert_type = 'danger';
            break;
        default:
            $alert_message = 'Terjadi kesalahan saat mengupdate status.';
            $alert_type = 'danger';
    }
}
// Function to format transaction code
function formatKodeTransaksi($id, $timestamp)
{
    $tanggal = date('Ymd', strtotime($timestamp));
    return 'TRX-' . $tanggal . '-' . str_pad($id, 4, '0', STR_PAD_LEFT);
}
?>

<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Pesanan - Admin Day Apparel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f4f7f6;
            /* Light gray background */
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            color: #333;
        }

        /* Content wrapper styles from other admin pages */
        #page-content-wrapper {
            flex-grow: 1;
            padding: 30px;
            background-color: #ffffff;
            /* White content background */
            border-radius: 12px;
            /* Softly rounded corners */
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            /* Subtle shadow */
            margin: 20px;
            /* Margin around the content area */
        }

        .main-header {
            font-size: 2.2rem;
            font-weight: 700;
            color: #2c3e50;
            /* Darker title color */
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #eee;
            /* Subtle separator */
            text-align: center;
        }

        /* Form & Select Styling */
        .form-select,
        .form-control {
            border-radius: 8px;
            /* Rounded input/select fields */
            padding: 10px 15px;
            border: 1px solid #ddd;
            transition: border-color 0.2s ease;
        }

        .form-select:focus,
        .form-control:focus {
            border-color: #34495e;
            /* Highlight border on focus */
            box-shadow: 0 0 0 0.25rem rgba(52, 73, 94, 0.25);
        }

        /* Button Styling */
        .btn-primary {
            background-color: #34495e;
            /* Darker blue/gray primary */
            border-color: #34495e;
            transition: all 0.3s ease;
            font-weight: 600;
            padding: 10px 20px;
            border-radius: 8px;
            /* Rounded buttons */
        }

        .btn-primary:hover {
            background-color: #2c3e50;
            border-color: #2c3e50;
            transform: translateY(-2px);
            /* Slight lift on hover */
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        }

        .btn-info {
            background-color: #3498db;
            /* Flat blue */
            border-color: #3498db;
            color: #fff;
            font-weight: 500;
            border-radius: 6px;
            transition: all 0.2s ease;
        }

        .btn-info:hover {
            background-color: #217dbb;
            border-color: #217dbb;
            color: #fff;
        }

        .btn-sm {
            padding: .3rem .75rem;
            /* Adjust small button padding */
            font-size: .875rem;
            border-radius: .4rem;
        }

        .btn-sm i {
            margin-right: 5px;
        }


        /* Table Styling */
        .table {
            background-color: #fff;
            border-radius: 10px;
            /* Rounded table corners */
            overflow: hidden;
            /* Ensures radius applies */
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
            /* Very light table shadow */
            margin-top: 20px;
        }

        .table thead th {
            background-color: #ecf0f1;
            /* Light header background */
            color: #555;
            font-weight: 600;
            border-bottom: 1px solid #dee2e6;
            padding: 12px 15px;
            text-transform: uppercase;
            font-size: 0.9em;
        }

        .table tbody tr:hover {
            background-color: #f9f9f9;
            /* Subtle hover effect */
        }

        .table td {
            padding: 12px 15px;
            vertical-align: middle;
            font-size: 0.95em;
        }

        /* Status Badges */
        .status-badge {
            display: inline-block;
            padding: .4em .7em;
            font-size: .8em;
            font-weight: 600;
            line-height: 1;
            color: #fff;
            text-align: center;
            white-space: nowrap;
            vertical-align: middle;
            border-radius: .4rem;
            text-transform: capitalize;
            /* Capitalize first letter */
        }

        .status-menunggu {
            background-color: #f39c12;
        }

        /* Orange */
        .status-dibayar {
            background-color: #2ecc71;
        }

        /* Green */
        .status-dikirim {
            background-color: #3498db;
        }

        /* Blue */
        .status-selesai {
            background-color: #1abc9c;
        }

        /* Turquoise */
        .status-dibatalkan {
            background-color: #e74c3c;
        }

        /* Red */


        /* Alert Styling */
        .alert {
            border-radius: 8px;
            /* Rounded alert corners */
            font-size: 1.05em;
            padding: 15px 20px;
            margin-bottom: 25px;
            /* Space below alert */
        }

        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border-color: #c3e6cb;
        }

        .alert-danger {
            background-color: #f8d7da;
            color: #721c24;
            border-color: #f5c6cb;
        }

        .alert-warning {
            background-color: #fff3cd;
            color: #856404;
            border-color: #ffeeba;
        }

        .alert .btn-close {
            font-size: 0.9em;
        }

        .resi-input {
            width: 120px !important;
            /* Make resi input smaller */
            margin-left: 5px;
        }

        .status-select {
            min-width: 200px !important;
            /* Lebar minimal lebih besar */
            width: auto !important;
            max-width: 100%;
            white-space: normal;
        }
    </style>
</head>

<body>
    <div id="wrapper">
        <?php // The sidebar.php content is included here 
        ?>
        <div id="page-content-wrapper">
            <div class="container-fluid">
                <h3 class="main-header">Kelola Pesanan</h3>

                <?php if ($alert_message): ?>
                    <div class="alert alert-<?= $alert_type ?> alert-dismissible fade show" role="alert">
                        <i class="fas fa-info-circle me-2"></i> <?= $alert_message ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <!-- Hapus card putih, filter status langsung di atas tabel -->
                <form class="row g-2 mb-3 align-items-center" method="get" style="max-width:320px;">
                    <div class="col-auto">
                        <label for="statusFilter" class="form-label mb-1" style="font-size:0.95em;">Filter Status</label>
                        <select name="status" id="statusFilter" class="form-select form-select-sm" style="min-width:160px;width:auto;display:inline-block;" onchange="this.form.submit()">
                            <option value="">-- Semua Status --</option>
                            <option value="menunggu" <?= $status_filter === 'menunggu' ? 'selected' : '' ?>>Menunggu Pembayaran</option>
                            <option value="dibayar" <?= $status_filter === 'dibayar' ? 'selected' : '' ?>>Sudah Dibayar</option>
                            <option value="dikirim" <?= $status_filter === 'dikirim' ? 'selected' : '' ?>>Sedang Dikirim</option>
                            <option value="selesai" <?= $status_filter === 'selesai' ? 'selected' : '' ?>>Selesai</option>
                            <option value="dibatalkan" <?= $status_filter === 'dibatalkan' ? 'selected' : '' ?>>Dibatalkan</option>
                        </select>
                    </div>
                </form>

                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>ID Pesanan</th>
                                <th>Pelanggan</th>
                                <th>Total Harga</th>
                                <th>Ongkir</th>
                                <th>Status</th>
                                <th>No. Resi</th>
                                <th>Bukti Bayar</th>
                                <th>Tanggal Pesan</th>
                                <th class="text-center">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($transaksi->num_rows > 0): ?>
                                <?php while ($t = $transaksi->fetch_assoc()) : ?>
                                    <tr>
                                        <td><?= formatKodeTransaksi($t['id'], $t['dibuat_pada']) ?></td>
                                        <td><?= htmlspecialchars($t['nama_pelanggan']) ?></td>
                                        <td>Rp<?= number_format($t['total_harga'], 0, ',', '.') ?></td>
                                        <td>Rp<?= number_format($t['ongkos_kirim'], 0, ',', '.') ?></td>
                                        <td>
                                            <span class="status-badge status-<?= htmlspecialchars($t['status']) ?>">
                                                <?= htmlspecialchars(ucwords(str_replace('_', ' ', $t['status']))) ?>
                                            </span>
                                        </td>
                                        <td><?= $t['resi'] ? htmlspecialchars($t['resi']) : '-' ?></td>
                                        <td>
                                            <?php if ($t['bukti_pembayaran']) : ?>
                                                <a href="../upload/<?= htmlspecialchars($t['bukti_pembayaran']) ?>" target="_blank" class="btn btn-sm btn-outline-info">
                                                    <i class="fas fa-image"></i> Lihat
                                                </a>
                                            <?php else : ?>
                                                <span class="text-muted">Belum ada</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?= htmlspecialchars($t['dibuat_pada']) ?></td>
                                        <td class="text-center">
                                            <a href="detail_pesanan.php?id=<?= htmlspecialchars($t['id']) ?>" class="btn btn-sm btn-info mb-1 w-100">
                                                <i class="fas fa-info-circle me-1"></i> Detail
                                            </a>
                                            <form action="../proses/proses_ubah_status.php" method="POST" class="mt-2">
                                                <input type="hidden" name="id" value="<?= htmlspecialchars($t['id']) ?>">
                                                <div class="d-flex flex-column align-items-stretch">
                                                    <select name="status" class="form-select form-select-sm mb-1 status-select">
                                                        <option value="menunggu" <?= $t['status'] == 'menunggu' ? 'selected' : '' ?>>Menunggu Pembayaran</option>
                                                        <option value="dibayar" <?= $t['status'] == 'dibayar' ? 'selected' : '' ?>>Dibayar</option>
                                                        <option value="dikirim" <?= $t['status'] == 'dikirim' ? 'selected' : '' ?>>Dikirim</option>
                                                        <option value="selesai" <?= $t['status'] == 'selesai' ? 'selected' : '' ?>>Selesai</option>
                                                        <option value="dibatalkan" <?= $t['status'] == 'dibatalkan' ? 'selected' : '' ?>>Dibatalkan</option>
                                                    </select>
                                                    <input type="text" name="resi" class="form-control form-control-sm mt-1 resi-input"
                                                        placeholder="Nomor Resi"
                                                        value="<?= htmlspecialchars($t['resi'] ?? '') ?>"
                                                        style="<?= $t['status'] === 'dikirim' ? 'display:inline-block;' : 'display:none;' ?>">
                                                    <button class="btn btn-sm btn-primary mt-1">
                                                        <i class="fas fa-sync-alt me-1"></i> Update Status
                                                    </button>
                                                </div>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="9" class="text-center py-4 text-muted">Tidak ada pesanan ditemukan dengan filter ini.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.querySelectorAll('.status-select').forEach(function(select) {
            const form = select.closest('form');
            const resiInput = form.querySelector('.resi-input');

            function toggleResiInput() {
                if (select.value === 'dikirim') {
                    resiInput.style.display = 'block'; // Use 'block' for better alignment in a column flex
                    resiInput.setAttribute('required', 'required'); // Make resi required if status is 'dikirim'
                } else {
                    resiInput.style.display = 'none';
                    resiInput.removeAttribute('required'); // Remove required if not 'dikirim'
                }
            }

            // Listen for change events on the select
            select.addEventListener('change', toggleResiInput);

            // Call the function once on page load to set initial state
            toggleResiInput();
        });

        // Add confirmation before form submission
        document.querySelectorAll('form[action*="proses_ubah_status.php"]').forEach(function(form) {
            form.addEventListener('submit', function(e) {
                const statusSelect = form.querySelector('.status-select');
                const resiInput = form.querySelector('.resi-input');
                const statusText = statusSelect.options[statusSelect.selectedIndex].text;

                let confirmMessage = `Apakah Anda yakin ingin mengubah status pesanan menjadi "${statusText}"?`;

                if (statusSelect.value === 'dikirim' && resiInput.value.trim() !== '') {
                    confirmMessage += `\nNomor resi: ${resiInput.value}`;
                }

                if (!confirm(confirmMessage)) {
                    e.preventDefault();
                    return false;
                }
            });
        });

        // Auto-hide alerts after 5 seconds
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                const bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            });
        }, 5000);
    </script>
</body>

</html>