<?php

declare(strict_types=1);

require_once __DIR__ . '/../../src/db.php';
require_once __DIR__ . '/../../src/SuperAdmin/SuperAdminAuth.php';
require_once __DIR__ . '/navigation.php';

SuperAdminAuth::requirePermission('discounts_view');

$admin = SuperAdminAuth::getCurrentAdmin();
$canManage = SuperAdminAuth::hasPermission('discounts_manage');
$pdo = getPDO();

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

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $canManage) {
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $code = strtoupper(trim($_POST['code'] ?? ''));
        $description = trim($_POST['description'] ?? '');
        $discountType = $_POST['discount_type'] ?? 'percent';
        $discountValue = (float)($_POST['discount_value'] ?? 0);
        $appliesTo = $_POST['applies_to'] ?? 'all';
        $maxUses = !empty($_POST['max_uses']) ? (int)$_POST['max_uses'] : null;
        $validFrom = !empty($_POST['valid_from']) ? $_POST['valid_from'] : null;
        $validUntil = !empty($_POST['valid_until']) ? $_POST['valid_until'] : null;

        if (empty($code) || $discountValue <= 0) {
            $error = 'Code and discount value are required.';
        } else {
            try {
                $stmt = $pdo->prepare('
                    INSERT INTO discount_codes (code, description, discount_type, discount_value, applies_to, max_uses, valid_from, valid_until, created_by)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                ');
                $stmt->execute([$code, $description, $discountType, $discountValue, $appliesTo, $maxUses, $validFrom, $validUntil, $admin['id']]);
                SuperAdminAuth::logActivity($admin['id'], 'create_discount', 'discount', (int)$pdo->lastInsertId(), ['code' => $code]);
                $message = 'Discount code created successfully.';
            } catch (Exception $e) {
                $error = 'Failed to create discount code. Code may already exist.';
            }
        }
    } elseif ($action === 'toggle') {
        $discountId = (int)($_POST['discount_id'] ?? 0);
        $isActive = (int)($_POST['is_active'] ?? 0);
        
        $stmt = $pdo->prepare('UPDATE discount_codes SET is_active = ? WHERE id = ?');
        if ($stmt->execute([$isActive, $discountId])) {
            SuperAdminAuth::logActivity($admin['id'], $isActive ? 'activate_discount' : 'deactivate_discount', 'discount', $discountId);
            $message = $isActive ? 'Discount activated.' : 'Discount deactivated.';
        } else {
            $error = 'Failed to update discount.';
        }
    } elseif ($action === 'delete') {
        $discountId = (int)($_POST['discount_id'] ?? 0);
        
        $stmt = $pdo->prepare('DELETE FROM discount_codes WHERE id = ?');
        if ($stmt->execute([$discountId])) {
            SuperAdminAuth::logActivity($admin['id'], 'delete_discount', 'discount', $discountId);
            $message = 'Discount deleted.';
        } else {
            $error = 'Failed to delete discount.';
        }
    }
}

// Get all discounts
$stmt = $pdo->query('SELECT * FROM discount_codes ORDER BY created_at DESC');
$discounts = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Discounts · Keelance Admin</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <script src="https://cdn.tailwindcss.com"></script>

</head>
<body class="bg-slate-100 min-h-screen text-slate-900">
<?php renderAdminNavigation(); ?>

<main class="flex-1">
    <div class="max-w-6xl mx-auto px-4 py-6 space-y-6">
        <div class="flex items-center justify-between gap-3">
            <div>
                <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Discount Codes</h1>
                <p class="text-slate-500 mt-1 text-sm">Manage promotional discounts and coupons for workspaces.</p>
            </div>
            <?php if ($canManage): ?>
                <button onclick="showCreateModal()" class="inline-flex items-center gap-1.5 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors">
                    <span class="text-base leading-none">＋</span>
                    <span>Create Discount</span>
                </button>
            <?php endif; ?>
        </div>

    <?php if ($message): ?>
        <div class="bg-emerald-500/10 border border-emerald-500/20 rounded-lg p-4 mb-6">
            <p class="text-sm text-emerald-400"><?= htmlspecialchars($message) ?></p>
        </div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="bg-red-500/10 border border-red-500/20 rounded-lg p-4 mb-6">
            <p class="text-sm text-red-400"><?= htmlspecialchars($error) ?></p>
        </div>
    <?php endif; ?>

    <!-- Discounts Table -->
    <div class="bg-white border border-slate-200 shadow-sm rounded-xl overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="text-left text-sm text-slate-500 border-b border-slate-200 bg-slate-50">
                        <th class="px-4 py-3 font-medium">Code</th>
                        <th class="px-4 py-3 font-medium">Discount</th>
                        <th class="px-4 py-3 font-medium">Applies To</th>
                        <th class="px-4 py-3 font-medium">Usage</th>
                        <th class="px-4 py-3 font-medium">Valid</th>
                        <th class="px-4 py-3 font-medium">Status</th>
                        <th class="px-4 py-3 font-medium text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php foreach ($discounts as $discount): ?>
                        <tr class="hover:bg-slate-50">
                            <td class="px-4 py-3">
                                <div>
                                    <p class="font-mono font-bold text-blue-400"><?= htmlspecialchars($discount['code']) ?></p>
                                    <p class="text-slate-500 text-xs"><?= htmlspecialchars($discount['description'] ?? '') ?></p>
                                </div>
                            </td>
                            <td class="px-6 py-4">
                                <span class="text-lg font-bold">
                                    <?php if ($discount['discount_type'] === 'percent'): ?>
                                        <?= $discount['discount_value'] ?>%
                                    <?php else: ?>
                                        $<?= number_format($discount['discount_value'], 2) ?>
                                    <?php endif; ?>
                                </span>
                            </td>
                            <td class="px-4 py-3 text-slate-700 capitalize">
                                <?= $discount['applies_to'] ?>
                            </td>
                            <td class="px-6 py-4">
                                <span class="text-slate-700"><?= $discount['used_count'] ?></span>
                                <span class="text-slate-500">/ <?= $discount['max_uses'] ?? '∞' ?></span>
                            </td>
                            <td class="px-4 py-3 text-sm text-slate-500">
                                <?php if ($discount['valid_from'] || $discount['valid_until']): ?>
                                    <?= $discount['valid_from'] ? date('M j', strtotime($discount['valid_from'])) : 'Start' ?>
                                    - 
                                    <?= $discount['valid_until'] ? date('M j', strtotime($discount['valid_until'])) : 'No end' ?>
                                <?php else: ?>
                                    Always
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4">
                                <?php if ($discount['is_active']): ?>
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-emerald-500/20 text-emerald-400">
                                        Active
                                    </span>
                                <?php else: ?>
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-slate-500/20 text-slate-500">
                                        Inactive
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4">
                                <?php if ($canManage): ?>
                                    <div class="flex items-center justify-end gap-2">
                                        <form method="POST" class="inline">
                                            <input type="hidden" name="action" value="toggle">
                                            <input type="hidden" name="discount_id" value="<?= $discount['id'] ?>">
                                            <input type="hidden" name="is_active" value="<?= $discount['is_active'] ? 0 : 1 ?>">
                                            <button type="submit" class="px-3 py-1.5 text-xs rounded-full border <?= $discount['is_active'] ? 'border-amber-300 text-amber-700 bg-white hover:bg-amber-50' : 'border-emerald-300 text-emerald-700 bg-white hover:bg-emerald-50' ?> transition-colors">
                                                <?= $discount['is_active'] ? 'Deactivate' : 'Activate' ?>
                                            </button>
                                        </form>
                                        <form method="POST" class="inline" onsubmit="return confirm('Delete this discount?')">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="discount_id" value="<?= $discount['id'] ?>">
                                            <button type="submit" class="px-3 py-1.5 text-xs rounded-full border border-red-300 text-red-700 bg-white hover:bg-red-50 transition-colors">
                                                Delete
                                            </button>
                                        </form>
                                    </div>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if (empty($discounts)): ?>
            <div class="text-center py-12">
                <p class="text-slate-500">No discount codes yet</p>
            </div>
        <?php endif; ?>
    </div>
</main>

<!-- Create Modal -->
<div id="createModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white border border-slate-200 shadow-sm rounded-xl p-6 w-full max-w-md mx-4">
        <h3 class="text-lg font-semibold mb-4">Create Discount Code</h3>
        <form method="POST" class="space-y-4">
            <input type="hidden" name="action" value="create">
            
            <div>
                <label class="block text-sm text-slate-500 mb-2">Code</label>
                <input type="text" name="code" required placeholder="SAVE20"
                       class="w-full px-4 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 uppercase focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div>
                <label class="block text-sm text-slate-500 mb-2">Description</label>
                <input type="text" name="description" placeholder="20% off for new users"
                       class="w-full px-4 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm text-slate-500 mb-2">Type</label>
                    <select name="discount_type" class="w-full px-4 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="percent">Percentage</option>
                        <option value="fixed">Fixed Amount</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm text-slate-500 mb-2">Value</label>
                    <input type="number" step="0.01" name="discount_value" required placeholder="20"
                           class="w-full px-4 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
            </div>
            
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm text-slate-500 mb-2">Applies To</label>
                    <select name="applies_to" class="w-full px-4 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="all">All Plans</option>
                        <option value="monthly">Monthly Only</option>
                        <option value="yearly">Yearly Only</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm text-slate-500 mb-2">Max Uses</label>
                    <input type="number" name="max_uses" placeholder="Unlimited"
                           class="w-full px-4 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
            </div>
            
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm text-slate-500 mb-2">Valid From</label>
                    <input type="date" name="valid_from"
                           class="w-full px-4 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                <div>
                    <label class="block text-sm text-slate-500 mb-2">Valid Until</label>
                    <input type="date" name="valid_until"
                           class="w-full px-4 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
            </div>
            
            <div class="flex gap-3 pt-4">
                <button type="button" onclick="closeCreateModal()" class="flex-1 px-4 py-2 bg-slate-50 hover:bg-slate-600 rounded-lg transition-colors">
                    Cancel
                </button>
                <button type="submit" class="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors">
                    Create
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function showCreateModal() {
    document.getElementById('createModal').classList.remove('hidden');
    document.getElementById('createModal').classList.add('flex');
}

function closeCreateModal() {
    document.getElementById('createModal').classList.add('hidden');
    document.getElementById('createModal').classList.remove('flex');
}
</script>
</body>
</html>
