<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';

require_admin();

$pageTitle = 'Shipping';
$success = '';
$error = '';
$editZone = null;
$editRate = null;

if (isset($_GET['created'])) {
    $success = 'Shipping record created successfully.';
}

if (isset($_GET['updated'])) {
    $success = 'Shipping record updated successfully.';
}

if (isset($_GET['deleted'])) {
    $success = 'Shipping record deleted successfully.';
}

if (isset($_GET['edit_zone'])) {
    $editId = (int) $_GET['edit_zone'];

    $stmt = $pdo->prepare("SELECT * FROM shipping_zones WHERE id = ? LIMIT 1");
    $stmt->execute([$editId]);
    $editZone = $stmt->fetch();

    if (!$editZone) {
        $error = 'Shipping zone not found.';
    }
}

if (isset($_GET['edit_rate'])) {
    $editId = (int) $_GET['edit_rate'];

    $stmt = $pdo->prepare("SELECT * FROM shipping_rates WHERE id = ? LIMIT 1");
    $stmt->execute([$editId]);
    $editRate = $stmt->fetch();

    if (!$editRate) {
        $error = 'Shipping rate not found.';
    }
}

if (isset($_GET['delete_zone'])) {
    $deleteId = (int) $_GET['delete_zone'];

    $stmt = $pdo->prepare("DELETE FROM shipping_rates WHERE zone_id = ?");
    $stmt->execute([$deleteId]);

    $stmt = $pdo->prepare("DELETE FROM shipping_zones WHERE id = ?");
    $stmt->execute([$deleteId]);

    redirect(ADMIN_URL . '/shipping.php?deleted=1');
}

if (isset($_GET['delete_rate'])) {
    $deleteId = (int) $_GET['delete_rate'];

    $stmt = $pdo->prepare("DELETE FROM shipping_rates WHERE id = ?");
    $stmt->execute([$deleteId]);

    redirect(ADMIN_URL . '/shipping.php?deleted=1');
}

if (is_post()) {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $formType = $_POST['form_type'] ?? '';

        if ($formType === 'zone') {
            $zoneId = (int) ($_POST['zone_id'] ?? 0);
            $zoneName = trim($_POST['zone_name'] ?? '');
            $country = trim($_POST['country'] ?? '');
            $region = trim($_POST['region'] ?? '');
            $message = trim($_POST['message'] ?? '');
            $status = $_POST['status'] ?? 'active';

            if ($zoneName === '') {
                $error = 'Zone name is required.';
            } elseif ($country === '') {
                $error = 'Country is required.';
            } elseif (!in_array($status, ['active', 'inactive'], true)) {
                $error = 'Invalid zone status.';
            } else {
                if ($zoneId > 0) {
                    $stmt = $pdo->prepare("
                        UPDATE shipping_zones
                        SET zone_name = ?,
                            country = ?,
                            region = ?,
                            message = ?,
                            status = ?
                        WHERE id = ?
                    ");

                    $stmt->execute([
                        $zoneName,
                        $country,
                        $region !== '' ? $region : null,
                        $message !== '' ? $message : null,
                        $status,
                        $zoneId
                    ]);

                    redirect(ADMIN_URL . '/shipping.php?updated=1');
                } else {
                    $stmt = $pdo->prepare("
                        INSERT INTO shipping_zones (
                            zone_name,
                            country,
                            region,
                            message,
                            status
                        ) VALUES (?, ?, ?, ?, ?)
                    ");

                    $stmt->execute([
                        $zoneName,
                        $country,
                        $region !== '' ? $region : null,
                        $message !== '' ? $message : null,
                        $status
                    ]);

                    redirect(ADMIN_URL . '/shipping.php?created=1');
                }
            }
        }

        if ($formType === 'rate') {
            $rateId = (int) ($_POST['rate_id'] ?? 0);
            $zoneId = (int) ($_POST['zone_id'] ?? 0);
            $rateName = trim($_POST['rate_name'] ?? '');
            $minOrderAmount = (float) ($_POST['min_order_amount'] ?? 0);
            $maxOrderAmount = $_POST['max_order_amount'] !== '' ? (float) $_POST['max_order_amount'] : null;
            $shippingFee = (float) ($_POST['shipping_fee'] ?? 0);
            $freeShippingThreshold = $_POST['free_shipping_threshold'] !== '' ? (float) $_POST['free_shipping_threshold'] : null;
            $status = $_POST['status'] ?? 'active';

            if ($zoneId <= 0) {
                $error = 'Please select a shipping zone.';
            } elseif ($rateName === '') {
                $error = 'Rate name is required.';
            } elseif ($shippingFee < 0) {
                $error = 'Shipping fee cannot be negative.';
            } elseif (!in_array($status, ['active', 'inactive'], true)) {
                $error = 'Invalid rate status.';
            } else {
                if ($rateId > 0) {
                    $stmt = $pdo->prepare("
                        UPDATE shipping_rates
                        SET zone_id = ?,
                            rate_name = ?,
                            min_order_amount = ?,
                            max_order_amount = ?,
                            shipping_fee = ?,
                            free_shipping_threshold = ?,
                            status = ?
                        WHERE id = ?
                    ");

                    $stmt->execute([
                        $zoneId,
                        $rateName,
                        $minOrderAmount,
                        $maxOrderAmount,
                        $shippingFee,
                        $freeShippingThreshold,
                        $status,
                        $rateId
                    ]);

                    redirect(ADMIN_URL . '/shipping.php?updated=1');
                } else {
                    $stmt = $pdo->prepare("
                        INSERT INTO shipping_rates (
                            zone_id,
                            rate_name,
                            min_order_amount,
                            max_order_amount,
                            shipping_fee,
                            free_shipping_threshold,
                            status
                        ) VALUES (?, ?, ?, ?, ?, ?, ?)
                    ");

                    $stmt->execute([
                        $zoneId,
                        $rateName,
                        $minOrderAmount,
                        $maxOrderAmount,
                        $shippingFee,
                        $freeShippingThreshold,
                        $status
                    ]);

                    redirect(ADMIN_URL . '/shipping.php?created=1');
                }
            }
        }
    }
}

$zones = $pdo->query("
    SELECT *
    FROM shipping_zones
    ORDER BY country ASC, zone_name ASC
")->fetchAll();

$rates = $pdo->query("
    SELECT sr.*, sz.zone_name, sz.country, sz.region
    FROM shipping_rates sr
    INNER JOIN shipping_zones sz ON sr.zone_id = sz.id
    ORDER BY sz.country ASC, sr.min_order_amount ASC, sr.id DESC
")->fetchAll();

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>Shipping</h1>
            <div class="admin-user">Manage shipping zones, delivery messages, rates, and free shipping thresholds.</div>
        </div>

        <?php if ($editZone || $editRate): ?>
            <a href="<?= e(ADMIN_URL); ?>/shipping.php" class="admin-btn admin-btn-light">Cancel Edit</a>
        <?php endif; ?>
    </div>

    <?php if ($success): ?>
        <div class="admin-alert admin-alert-success"><?= e($success); ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="admin-alert admin-alert-error"><?= e($error); ?></div>
    <?php endif; ?>

    <section class="admin-panel" style="margin-bottom:24px;">
        <h2><?= $editZone ? 'Edit Shipping Zone' : 'Add Shipping Zone'; ?></h2>

        <form method="POST">
            <?= csrf_field(); ?>

            <input type="hidden" name="form_type" value="zone">
            <input type="hidden" name="zone_id" value="<?= e($editZone['id'] ?? 0); ?>">

            <div class="admin-form-grid">
                <div class="admin-field">
                    <label>Zone Name *</label>
                    <input type="text" name="zone_name" value="<?= e($editZone['zone_name'] ?? ''); ?>" placeholder="United Kingdom Standard" required>
                </div>

                <div class="admin-field">
                    <label>Country *</label>
                    <input type="text" name="country" value="<?= e($editZone['country'] ?? ''); ?>" placeholder="United Kingdom" required>
                </div>

                <div class="admin-field">
                    <label>Region</label>
                    <input type="text" name="region" value="<?= e($editZone['region'] ?? ''); ?>" placeholder="London / England / All">
                </div>

                <div class="admin-field">
                    <label>Status</label>
                    <select name="status">
                        <option value="active" <?= ($editZone['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?= ($editZone['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>
            </div>

            <div class="admin-field">
                <label>Checkout Message</label>
                <textarea name="message" placeholder="Delivery usually takes 2-4 working days."><?= e($editZone['message'] ?? ''); ?></textarea>
            </div>

            <button type="submit" class="admin-btn">
                <?= $editZone ? 'Update Zone' : 'Create Zone'; ?>
            </button>
        </form>
    </section>

    <section class="admin-panel" style="margin-bottom:24px;">
        <h2><?= $editRate ? 'Edit Shipping Rate' : 'Add Shipping Rate'; ?></h2>

        <form method="POST">
            <?= csrf_field(); ?>

            <input type="hidden" name="form_type" value="rate">
            <input type="hidden" name="rate_id" value="<?= e($editRate['id'] ?? 0); ?>">

            <div class="admin-form-grid">
                <div class="admin-field">
                    <label>Shipping Zone *</label>
                    <select name="zone_id" required>
                        <option value="">Select Zone</option>
                        <?php foreach ($zones as $zone): ?>
                            <option value="<?= e($zone['id']); ?>" <?= isset($editRate['zone_id']) && (int)$editRate['zone_id'] === (int)$zone['id'] ? 'selected' : ''; ?>>
                                <?= e($zone['zone_name']); ?> — <?= e($zone['country']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="admin-field">
                    <label>Rate Name *</label>
                    <input type="text" name="rate_name" value="<?= e($editRate['rate_name'] ?? ''); ?>" placeholder="Standard Shipping" required>
                </div>

                <div class="admin-field">
                    <label>Minimum Order Amount</label>
                    <input type="number" step="0.01" name="min_order_amount" value="<?= e($editRate['min_order_amount'] ?? 0); ?>">
                </div>

                <div class="admin-field">
                    <label>Maximum Order Amount</label>
                    <input type="number" step="0.01" name="max_order_amount" value="<?= e($editRate['max_order_amount'] ?? ''); ?>" placeholder="Leave empty for no max">
                </div>

                <div class="admin-field">
                    <label>Shipping Fee</label>
                    <input type="number" step="0.01" name="shipping_fee" value="<?= e($editRate['shipping_fee'] ?? 0); ?>">
                </div>

                <div class="admin-field">
                    <label>Free Shipping Threshold</label>
                    <input type="number" step="0.01" name="free_shipping_threshold" value="<?= e($editRate['free_shipping_threshold'] ?? ''); ?>" placeholder="Example: 50.00">
                </div>

                <div class="admin-field">
                    <label>Status</label>
                    <select name="status">
                        <option value="active" <?= ($editRate['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?= ($editRate['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>
            </div>

            <button type="submit" class="admin-btn">
                <?= $editRate ? 'Update Rate' : 'Create Rate'; ?>
            </button>
        </form>
    </section>

    <section class="admin-panel" style="margin-bottom:24px;">
        <h2>Shipping Zones</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Zone</th>
                    <th>Country</th>
                    <th>Region</th>
                    <th>Message</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$zones): ?>
                    <tr>
                        <td colspan="6">No shipping zones created yet.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($zones as $zone): ?>
                    <tr>
                        <td><strong><?= e($zone['zone_name']); ?></strong></td>
                        <td><?= e($zone['country']); ?></td>
                        <td><?= e($zone['region'] ?? '-'); ?></td>
                        <td><?= e($zone['message'] ?? '-'); ?></td>
                        <td><?= e(ucfirst($zone['status'])); ?></td>
                        <td>
                            <a class="admin-btn admin-btn-light" href="<?= e(ADMIN_URL); ?>/shipping.php?edit_zone=<?= e($zone['id']); ?>">Edit</a>

                            <a
                                class="admin-btn"
                                href="<?= e(ADMIN_URL); ?>/shipping.php?delete_zone=<?= e($zone['id']); ?>"
                                onclick="return confirm('Delete this zone and its rates?');"
                            >
                                Delete
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>

    <section class="admin-panel">
        <h2>Shipping Rates</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Rate</th>
                    <th>Zone</th>
                    <th>Order Range</th>
                    <th>Fee</th>
                    <th>Free Over</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$rates): ?>
                    <tr>
                        <td colspan="7">No shipping rates created yet.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($rates as $rate): ?>
                    <tr>
                        <td><strong><?= e($rate['rate_name']); ?></strong></td>
                        <td>
                            <?= e($rate['zone_name']); ?><br>
                            <small><?= e($rate['country']); ?><?= !empty($rate['region']) ? ' · ' . e($rate['region']) : ''; ?></small>
                        </td>
                        <td>
                            <?= e(format_price($rate['min_order_amount'] ?? 0)); ?>
                            -
                            <?= !empty($rate['max_order_amount']) ? e(format_price($rate['max_order_amount'])) : 'No max'; ?>
                        </td>
                        <td><?= e(format_price($rate['shipping_fee'] ?? 0)); ?></td>
                        <td>
                            <?= !empty($rate['free_shipping_threshold'])
                                ? e(format_price($rate['free_shipping_threshold']))
                                : 'No free shipping'; ?>
                        </td>
                        <td><?= e(ucfirst($rate['status'])); ?></td>
                        <td>
                            <a class="admin-btn admin-btn-light" href="<?= e(ADMIN_URL); ?>/shipping.php?edit_rate=<?= e($rate['id']); ?>">Edit</a>

                            <a
                                class="admin-btn"
                                href="<?= e(ADMIN_URL); ?>/shipping.php?delete_rate=<?= e($rate['id']); ?>"
                                onclick="return confirm('Delete this shipping rate?');"
                            >
                                Delete
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>

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