<?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_appliance':
                $name = trim($_POST['name'] ?? '');
                $sort = (int)($_POST['sort_order'] ?? 0);
                $default_icon = 'fas fa-tools';

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

                $stmt = $db->prepare("
                    INSERT INTO appliance_types 
                        (name, icon_class, sort_order) 
                    VALUES 
                        (:name, :icon_class, :sort_order)
                ");

                $stmt->execute([
                    ':name' => $name,
                    ':icon_class' => $default_icon,
                    ':sort_order' => $sort
                ]);

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

            case 'edit_appliance':
                $stmt = $db->prepare("
                    UPDATE appliance_types 
                    SET 
                        name = :name, 
                        sort_order = :sort_order 
                    WHERE id = :id
                ");

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

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

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

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

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

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

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

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

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

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Appliances - 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-header strong,
        .card-header h5,
        .card-header h6 {
            color: #ffffff !important;
            font-weight: 900;
        }

        .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;
        }

        .btn-secondary {
            background: rgba(148, 163, 184, 0.22) !important;
            border: 1px solid rgba(148, 163, 184, 0.30) !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 small {
            color: var(--admin-muted) !important;
        }

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

        .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-tools me-2"></i>
                    Manage Appliances
                </h2>

                <p class="text-muted mb-0">
                    Add, edit, and manage appliance types shown in service requests.
                </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 Appliances</h6>
                                <h3 class="mb-0"><?= number_format($total_appliances) ?></h3>
                            </div>

                            <div class="stat-icon-box">
                                <i class="fas fa-tools"></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 Types</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 Types</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 Appliance
            </div>

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

                    <div class="col-md-8">
                        <label class="form-label">Appliance Name</label>
                        <input 
                            class="form-control" 
                            name="name" 
                            placeholder="Enter appliance name" 
                            required
                        >
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Sort Order</label>
                        <input 
                            type="number" 
                            class="form-control" 
                            name="sort_order" 
                            placeholder="Sort" 
                            value="0"
                        >
                    </div>

                    <div class="col-md-1 d-flex align-items-end">
                        <button class="btn btn-primary w-100" title="Add Appliance">
                            <i class="fas fa-plus"></i>
                        </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>
                    Appliance List
                </span>

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

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

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

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

                                    <td style="width: 160px;">
                                        <input 
                                            type="number" 
                                            class="form-control" 
                                            name="sort_order" 
                                            value="<?= (int)$a['sort_order'] ?>"
                                        >
                                    </td>

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

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

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

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

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

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