<?php
require_once __DIR__ . '/../includes/auth.php';
require_owner_or_admin();
require_once __DIR__ . '/../includes/header_admin.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$errors = [];
$editRate = null;

if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare('SELECT * FROM shipping_rates WHERE id = ?');
    $stmt->execute([(int)$_GET['edit']]);
    $editRate = $stmt->fetch();
}

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

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare('DELETE FROM shipping_rates WHERE id = ? AND is_default = 0')->execute([$id]);
        flash_message('success', 'Lokasi berhasil dihapus.');
        redirect(base_url('admin/shipping.php'));
    }

    if ($action === 'save') {
        $id = (int)($_POST['id'] ?? 0);
        $location = trim($_POST['location_name'] ?? '');
        $cost = (float)($_POST['cost'] ?? 0);
        $is_default = isset($_POST['is_default']) ? 1 : 0;

        if ($location === '') $errors['location'] = 'Nama lokasi wajib diisi.';

        if (!$errors) {
            if ($is_default) {
                // Unset other defaults if this one becomes default
                $pdo->exec('UPDATE shipping_rates SET is_default = 0');
            }

            if ($id === 0) {
                $stmt = $pdo->prepare('INSERT INTO shipping_rates (location_name, cost, is_default) VALUES (?, ?, ?)');
                $stmt->execute([$location, $cost, $is_default]);
            } else {
                $stmt = $pdo->prepare('UPDATE shipping_rates SET location_name = ?, cost = ?, is_default = ? WHERE id = ?');
                $stmt->execute([$location, $cost, $is_default, $id]);
            }
            flash_message('success', 'Data ongkir tersimpan.');
            redirect(base_url('admin/shipping.php'));
        }
    }
}

$rates = $pdo->query('SELECT * FROM shipping_rates ORDER BY is_default DESC, location_name ASC')->fetchAll();
?>

<h2 class="fw-bold mb-4">Manajemen Ongkir</h2>

<div class="row">
    <div class="col-md-4">
        <div class="card shadow-sm mb-4">
            <div class="card-body">
                <h5 class="fw-bold"><?= $editRate ? 'Edit Lokasi' : 'Tambah Lokasi Baru'; ?></h5>
                <form method="post">
                    <input type="hidden" name="action" value="save">
                    <input type="hidden" name="id" value="<?= $editRate ? (int)$editRate['id'] : 0; ?>">
                    
                    <div class="mb-3">
                        <label>Nama Lokasi / Area</label>
                        <input type="text" class="form-control" name="location_name" value="<?= $editRate ? sanitize($editRate['location_name']) : ''; ?>" placeholder="Misal: Kecamatan Kuranji" required>
                    </div>

                    <div class="mb-3">
                        <label>Biaya Ongkir (Rp)</label>
                        <input type="number" class="form-control" name="cost" value="<?= $editRate ? (float)$editRate['cost'] : 0; ?>" required>
                    </div>

                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="is_default" id="defCheck" <?= ($editRate && $editRate['is_default']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="defCheck">Set sebagai Default (Luar Kota)</label>
                    </div>

                    <button class="btn btn-primary w-100">Simpan</button>
                    <?php if($editRate): ?>
                        <a href="<?= base_url('admin/shipping.php'); ?>" class="btn btn-outline-secondary w-100 mt-2">Batal</a>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-8">
        <div class="card shadow-sm">
            <div class="card-body table-responsive">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th>Lokasi</th>
                            <th>Ongkir</th>
                            <th>Status</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($rates as $r): ?>
                        <tr>
                            <td>
                                <?= sanitize($r['location_name']); ?>
                                <?php if($r['is_default']): ?>
                                    <span class="badge bg-warning text-dark ms-2">Default</span>
                                <?php endif; ?>
                            </td>
                            <td><?= format_currency($r['cost']); ?></td>
                            <td>
                                <span class="badge bg-success">Aktif</span>
                            </td>
                            <td>
                                <a href="?edit=<?= $r['id']; ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-pencil me-1"></i> Edit</a>
                                <?php if(!$r['is_default']): ?>
                                <form method="post" class="d-inline" onsubmit="return confirm('Hapus lokasi ini?');">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $r['id']; ?>">
                                    <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash me-1"></i> Hapus</button>
                                </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer_admin.php'; ?>
