<?php
require_once 'auth.php';
ensureAdminAuth();

require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    try {
        switch ($_POST['action']) {
            case 'add_brand':
                $name = trim($_POST['name'] ?? '');

                if ($name === '') {
                    throw new Exception('Brand name is required.');
                }

                $stmt = $db->prepare("
                    INSERT INTO brands 
                        (name, logo_url) 
                    VALUES 
                        (:name, NULL)
                ");

                $stmt->execute([
                    ':name' => $name
                ]);

                $success_message = 'Brand added successfully!';
                break;

            case 'edit_brand':
                $name = trim($_POST['name'] ?? '');

                if ($name === '') {
                    throw new Exception('Brand name is required.');
                }

                $stmt = $db->prepare("
                    UPDATE brands 
                    SET name = :name
                    WHERE id = :id
                ");

                $stmt->execute([
                    ':id' => (int)$_POST['id'],
                    ':name' => $name
                ]);

                $success_message = 'Brand updated successfully!';
                break;

            case 'delete_brand':
                $check = $db->prepare("
                    SELECT COUNT(*) 
                    FROM service_requests 
                    WHERE brand_id = :id
                ");

                $check->execute([
                    ':id' => (int)$_POST['id']
                ]);

                if ((int)$check->fetchColumn() > 0) {
                    throw new Exception('This brand is already used in service requests. Rename it instead of deleting it.');
                }

                $stmt = $db->prepare("
                    DELETE FROM brands 
                    WHERE id = :id
                ");

                $stmt->execute([
                    ':id' => (int)$_POST['id']
                ]);

                $success_message = 'Brand deleted successfully!';
                break;
        }
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

$brands = $db->query("
    SELECT 
        b.*, 
        COUNT(sr.id) AS request_count 
    FROM brands b 
    LEFT JOIN service_requests sr ON sr.brand_id = b.id 
    GROUP BY b.id 
    ORDER BY b.name ASC
")->fetchAll(PDO::FETCH_ASSOC);

$total_brands = count($brands);
$total_used = count(array_filter($brands, function($b) {
    return (int)$b['request_count'] > 0;
}));
$total_unused = $total_brands - $total_used;
$total_requests = array_sum(array_map(function($b) {
    return (int)$b['request_count'];
}, $brands));
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Brands - Admin</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">

    <style>
        :root {
            --admin-bg-1: #080240;
            --admin-bg-2: #093349;
            --admin-card-1: #17295e;
            --admin-card-2: #102448;
            --admin-border: rgba(96, 165, 250, 0.24);
            --admin-border-strong: rgba(56, 189, 248, 0.42);
            --admin-cyan: #17bdd4;
            --admin-blue: #1d9bf0;
            --admin-text: #f8fafc;
            --admin-muted: #aebbd4;
            --admin-soft: #d7e7ff;
            --admin-green: #22c55e;
            --admin-yellow: #facc15;
            --admin-red: #f43f5e;
            --admin-input: rgba(8, 20, 48, 0.72);
        }

        * {
            box-sizing: border-box;
        }

        body {
            background: linear-gradient(135deg, var(--admin-bg-1) 0%, var(--admin-bg-2) 100%) fixed !important;
            color: var(--admin-text) !important;
            font-family: 'Montserrat', sans-serif !important;
            min-height: 100vh;
            overflow-x: hidden;
        }

        .sidebar {
            min-height: 100vh;
            background: rgba(8, 2, 64, 0.96);
            backdrop-filter: blur(14px);
            color: white;
            position: fixed;
            width: 250px;
            transition: all 0.3s;
            overflow-y: auto;
            z-index: 1000;
            border-right: 1px solid rgba(96, 165, 250, 0.18);
        }

        .sidebar-header {
            padding: 24px 18px;
            text-align: center;
            border-bottom: 1px solid rgba(96, 165, 250, 0.18);
        }

        .sidebar-header i {
            color: #ffffff;
        }

        .sidebar-header h4 {
            font-size: 1.1rem;
            margin-top: 10px;
            font-weight: 900;
            color: #ffffff;
        }

        .sidebar-header p {
            font-size: 0.8rem;
            color: var(--admin-muted);
        }

        .sidebar-menu {
            padding: 20px 0;
        }

        .sidebar-menu a {
            color: #b9dcff !important;
            padding: 13px 20px;
            display: block;
            text-decoration: none;
            transition: all 0.25s;
            border-left: 4px solid transparent;
            font-weight: 700;
            font-size: 14px;
        }

        .sidebar-menu a:hover,
        .sidebar-menu a.active {
            background: rgba(56, 189, 248, 0.12);
            color: #ffffff !important;
            border-left-color: var(--admin-cyan);
        }

        .sidebar-menu i {
            margin-right: 10px;
            width: 20px;
        }

        .main-content {
            margin-left: 250px;
            padding: 24px;
            min-height: 100vh;
            background: transparent !important;
        }

        .content-header {
            background: linear-gradient(135deg, var(--admin-card-1), var(--admin-card-2)) !important;
            padding: 20px;
            border-radius: 18px;
            border: 1px solid rgba(56, 189, 248, 0.28);
            box-shadow: 0 10px 24px rgba(0, 0, 0, 0.24);
            margin-bottom: 20px;
            color: #ffffff !important;
        }

        .content-header h2 {
            color: #ffffff !important;
            font-weight: 900;
        }

        .content-header h2 i {
            color: var(--admin-cyan) !important;
        }

        .content-header p,
        .text-muted {
            color: var(--admin-muted) !important;
        }

        .card {
            background: linear-gradient(135deg, var(--admin-card-1), var(--admin-card-2)) !important;
            border: 1px solid rgba(56, 189, 248, 0.24) !important;
            border-radius: 16px !important;
            box-shadow:
                0 10px 24px rgba(0, 0, 0, 0.24),
                inset 0 0 0 1px rgba(255, 255, 255, 0.025) !important;
            color: #ffffff !important;
            overflow: hidden;
            transition: all 0.25s ease;
        }

        .card:hover {
            border-color: rgba(56, 189, 248, 0.38) !important;
        }

        .card-header,
        .card-header.bg-white {
            background: linear-gradient(135deg, rgba(29, 155, 240, 0.16), rgba(23, 189, 212, 0.08)) !important;
            border-bottom: 1px solid rgba(56, 189, 248, 0.22) !important;
            padding: 15px 20px;
            font-weight: 900;
            color: #ffffff !important;
        }

        .card-body {
            padding: 20px;
            color: #ffffff !important;
        }

        h1, h2, h3, h4, h5, h6, strong, label {
            color: #ffffff !important;
        }

        .stat-card {
            height: 100%;
        }

        .stat-card:hover {
            transform: translateY(-3px);
        }

        .stat-icon-box {
            background: rgba(56, 189, 248, 0.14) !important;
            border: 1px solid rgba(56, 189, 248, 0.22);
            border-radius: 12px;
            width: 48px;
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .stat-icon-box i {
            color: #dff7ff !important;
            font-size: 20px;
        }

        .form-control,
        .form-select,
        textarea,
        input {
            background-color: var(--admin-input) !important;
            border: 1px solid rgba(96, 165, 250, 0.34) !important;
            color: #ffffff !important;
            border-radius: 10px !important;
            min-height: 42px;
        }

        .form-control::placeholder,
        input::placeholder,
        textarea::placeholder {
            color: #aebbd4 !important;
            opacity: 1;
        }

        .form-control:focus,
        .form-select:focus {
            border-color: rgba(56, 189, 248, 0.62) !important;
            box-shadow: 0 0 0 0.18rem rgba(56, 189, 248, 0.18) !important;
        }

        .btn {
            font-weight: 800 !important;
            border-radius: 10px !important;
        }

        .btn-primary,
        .btn-info {
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
            border: none !important;
            color: #ffffff !important;
        }

        .btn-warning {
            background: linear-gradient(135deg, #f59e0b 0%, #facc15 100%) !important;
            border: none !important;
            color: #111827 !important;
        }

        .btn-danger {
            background: linear-gradient(135deg, #dc2626 0%, #f43f5e 100%) !important;
            border: none !important;
            color: #ffffff !important;
        }

        .badge {
            padding: 6px 10px;
            border-radius: 999px;
            font-weight: 900;
        }

        .badge.bg-primary {
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
            color: #ffffff !important;
        }

        .badge.bg-info {
            background: rgba(56, 189, 248, 0.18) !important;
            color: #dff7ff !important;
            border: 1px solid rgba(56, 189, 248, 0.34);
        }

        .badge.bg-success {
            background: rgba(34, 197, 94, 0.18) !important;
            color: #bbf7d0 !important;
            border: 1px solid rgba(34, 197, 94, 0.34);
        }

        .badge.bg-secondary {
            background: rgba(148, 163, 184, 0.20) !important;
            border: 1px solid rgba(148, 163, 184, 0.34);
            color: #e2e8f0 !important;
        }

        .alert {
            border-radius: 14px;
            border: 1px solid rgba(56, 189, 248, 0.28) !important;
        }

        .alert-success {
            background: rgba(34, 197, 94, 0.14) !important;
            color: #bbf7d0 !important;
        }

        .alert-danger {
            background: rgba(244, 63, 94, 0.14) !important;
            color: #fecaca !important;
        }

        .table-responsive {
            border-radius: 12px;
            overflow-x: auto;
            background: transparent !important;
        }

        .table {
            color: var(--admin-text) !important;
            margin-bottom: 0 !important;
        }

        .table th {
            font-weight: 900;
            color: #ffffff !important;
            white-space: nowrap;
            background: rgba(8, 20, 48, 0.58) !important;
            border-color: rgba(96, 165, 250, 0.22) !important;
            font-size: 13px;
        }

        .table td {
            vertical-align: middle;
            color: var(--admin-soft) !important;
            border-color: rgba(96, 165, 250, 0.20) !important;
            background: rgba(8, 20, 48, 0.18) !important;
        }

        .table tbody tr:hover td {
            background: rgba(56, 189, 248, 0.10) !important;
            color: #ffffff !important;
        }

        .table strong {
            color: #ffffff !important;
        }

        .brand-preview {
            min-width: 42px;
            height: 42px;
            border-radius: 12px;
            background: rgba(56, 189, 248, 0.14);
            border: 1px solid rgba(56, 189, 248, 0.28);
            color: #dff7ff;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: 900;
            padding: 0 10px;
        }

        .action-buttons {
            display: flex;
            gap: 6px;
            align-items: center;
            white-space: nowrap;
        }

        .id-pill {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 48px;
            padding: 6px 10px;
            border-radius: 999px;
            background: rgba(56, 189, 248, 0.14);
            border: 1px solid rgba(56, 189, 248, 0.28);
            color: #dff7ff;
            font-weight: 900;
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: relative;
                min-height: auto;
            }

            .main-content {
                margin-left: 0;
                padding: 14px;
            }

            .content-header {
                padding: 15px;
                display: block !important;
            }

            .content-header > div:last-child {
                margin-top: 12px;
            }

            .content-header h2 {
                font-size: 1.3rem;
            }

            .card-body {
                padding: 15px;
            }

            .table {
                min-width: 760px;
            }
        }
    </style>

    <link rel="stylesheet" href="../assets/theme.css">
    <link rel="stylesheet" href="../assets/portal-dark.css">
    <link rel="stylesheet" href="../assets/ushs-global-theme.css">
    <link rel="stylesheet" href="../assets/admin-sidebar.css">
</head>

<body>
    <?php require_once __DIR__ . '/admin_sidebar.php'; render_admin_sidebar(); ?>

    <main class="main-content">
        <div class="content-header d-flex justify-content-between align-items-center">
            <div>
                <h2 class="mb-1">
                    <i class="fas fa-tag me-2"></i>
                    Manage Brands
                </h2>

                <p class="text-muted mb-0">
                    Add, edit, and manage serviceable appliance brands.
                </p>
            </div>

            <div>
                <span class="badge bg-primary p-2">
                    <i class="fas fa-calendar me-1"></i>
                    <?= date('M d, Y') ?>
                </span>
            </div>
        </div>

        <?php if($success_message): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle me-2"></i>
                <?= htmlspecialchars($success_message) ?>
            </div>
        <?php endif; ?>

        <?php if($error_message): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?= htmlspecialchars($error_message) ?>
            </div>
        <?php endif; ?>

        <div class="row mb-4">
            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-muted mb-1">Total Brands</h6>
                                <h3 class="mb-0"><?= number_format($total_brands) ?></h3>
                            </div>

                            <div class="stat-icon-box">
                                <i class="fas fa-tag"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-muted mb-1">Used Brands</h6>
                                <h3 class="mb-0"><?= number_format($total_used) ?></h3>
                            </div>

                            <div class="stat-icon-box">
                                <i class="fas fa-check-circle"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-muted mb-1">Unused Brands</h6>
                                <h3 class="mb-0"><?= number_format($total_unused) ?></h3>
                            </div>

                            <div class="stat-icon-box">
                                <i class="fas fa-circle-minus"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-muted mb-1">Total Requests</h6>
                                <h3 class="mb-0"><?= number_format($total_requests) ?></h3>
                            </div>

                            <div class="stat-icon-box">
                                <i class="fas fa-clipboard-list"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header">
                <i class="fas fa-plus-circle me-2" style="color: var(--admin-cyan);"></i>
                Add New Brand
            </div>

            <div class="card-body">
                <form method="POST" class="row g-3">
                    <input type="hidden" name="action" value="add_brand">

                    <div class="col-md-10">
                        <label class="form-label">Brand Name</label>
                        <input 
                            class="form-control" 
                            name="name" 
                            placeholder="Enter brand name" 
                            required
                        >
                    </div>

                    <div class="col-md-2 d-flex align-items-end">
                        <button class="btn btn-primary w-100">
                            <i class="fas fa-plus me-1"></i>
                            Add Brand
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span>
                    <i class="fas fa-list me-2" style="color: var(--admin-cyan);"></i>
                    Brand List
                </span>

                <span class="badge bg-info">
                    <?= number_format($total_brands) ?> records
                </span>
            </div>

            <div class="card-body table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Brand Name</th>
                            <th>Requests</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php foreach($brands as $b): ?>
                            <tr>
                                <form method="POST">
                                    <td>
                                        <span class="id-pill">
                                            #<?= (int)$b['id'] ?>
                                        </span>
                                    </td>

                                    <td>
                                        <div class="d-flex align-items-center gap-2">
                                            <span class="brand-preview">
                                                <?= htmlspecialchars(strtoupper(substr($b['name'], 0, 2))) ?>
                                            </span>

                                            <input 
                                                class="form-control" 
                                                name="name" 
                                                value="<?= htmlspecialchars($b['name']) ?>" 
                                                required
                                            >
                                        </div>
                                    </td>

                                    <td>
                                        <span class="badge bg-info">
                                            <?= (int)$b['request_count'] ?>
                                        </span>
                                    </td>

                                    <td>
                                        <?= !empty($b['created_at']) ? htmlspecialchars(date('M d, Y', strtotime($b['created_at']))) : 'N/A' ?>
                                    </td>

                                    <td>
                                        <div class="action-buttons">
                                            <input type="hidden" name="id" value="<?= (int)$b['id'] ?>">

                                            <button 
                                                name="action" 
                                                value="edit_brand" 
                                                class="btn btn-sm btn-warning" 
                                                title="Save Changes"
                                            >
                                                <i class="fas fa-save"></i>
                                            </button>

                                            <button 
                                                name="action" 
                                                value="delete_brand" 
                                                onclick="return confirm('Delete this brand?')"
                                                class="btn btn-sm btn-danger" 
                                                title="Delete Brand"
                                            >
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </form>
                            </tr>
                        <?php endforeach; ?>

                        <?php if(empty($brands)): ?>
                            <tr>
                                <td colspan="5" class="text-center text-muted py-4">
                                    <i class="fas fa-tag fa-2x mb-2"></i><br>
                                    No brands found.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</body>
</html>