<?php
session_start();
$message = $_SESSION['message'] ?? null;
$message_type = $_SESSION['message_type'] ?? null;
unset($_SESSION['message'], $_SESSION['message_type']);

require_once __DIR__ . '/db/config.php';

// Get status from query string
$status_filter = $_GET['status'] ?? null;
$page_title = "Painel de Controle";
if ($status_filter === 'Manutencao') {
    $page_title = "Instalações em Manutenção";
}

try {
    $pdo = db();

    // Base query
    $query = "
        SELECT 
            i.*, 
            (SELECT ii.image_path FROM installation_images ii WHERE ii.installation_id = i.id ORDER BY ii.id ASC LIMIT 1) as first_image
        FROM 
            installations i
    ";

    // Apply status filter if present
    if ($status_filter) {
        $query .= " WHERE i.status = :status";
    }

    $query .= " ORDER BY i.created_at DESC";

    $stmt = $pdo->prepare($query);

    if ($status_filter) {
        $stmt->bindParam(':status', $status_filter, PDO::PARAM_STR);
    }

    $stmt->execute();
    $installations = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Calculate KPIs
    $kpi_query = "
        SELECT 
            (SELECT COUNT(*) FROM installations) as total,
            (SELECT COUNT(*) FROM installations WHERE status = 'ativo') as active,
            (SELECT COUNT(*) FROM installations WHERE status = 'Manutencao') as maintenance,
            (SELECT COUNT(*) FROM installations WHERE status = 'Manutenção Parcial') as partial_maintenance
    ";
    $kpi_stmt = $pdo->query($kpi_query);
    $kpis = $kpi_stmt->fetch(PDO::FETCH_ASSOC);

    $total_installations = $kpis['total'] ?? 0;
    $active_installations = $kpis['active'] ?? 0;
    $maintenance_installations = $kpis['maintenance'] ?? 0;
    $partial_maintenance_installations = $kpis['partial_maintenance'] ?? 0;

} catch (Exception $e) {
    $installations = [];
    $total_installations = 0;
    $active_installations = 0;
    $maintenance_installations = 0;
    $db_error = "Falha na conexão com o banco de dados ou tabela não encontrada. Por favor, execute a migração.";
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>iload net Solutions - <?php echo $page_title; ?></title>
    <meta name="description" content="Painel para gerenciamento de instalações de carregadores de veículos elétricos.">
    <meta name="keywords" content="EV charger, installation management, maintenance log, ILOADNET, dashboard, electric vehicle, fleet management, charge point operator, Built with Flatlogic Generator">
    <meta property="og:title" content="iload net Solutions">
    <meta property="og:description" content="Painel para gerenciamento de instalações de carregadores de veículos elétricos.">
    <meta property="og:image" content="<?php echo $_SERVER['PROJECT_IMAGE_URL']; ?>">
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:image" content="<?php echo $_SERVER['PROJECT_IMAGE_URL']; ?>">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
</head>
<body>

    <div class="sidebar">
        <a class="navbar-brand" href="index.php">iload net Solutions</a>
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link active" href="index.php">
                    <i class="bi bi-grid-1x2-fill"></i> Painel de Controle
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="add_installation.php">
                    <i class="bi bi-plus-circle-fill"></i> Adicionar Instalação
                </a>
            </li>
        </ul>
    </div>

    <div class="main-content">
        <nav class="top-navbar navbar navbar-expand">
            <div class="container-fluid">
                <form class="d-flex me-auto" role="search">
                    <input class="form-control me-2" type="search" placeholder="Buscar por..." aria-label="Search">
                </form>
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bi bi-person-circle me-1"></i> Administrador
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="#">Perfil</a></li>
                            <li><a class="dropdown-item" href="#">Sair</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </nav>

        <div class="container-fluid">
            <?php if (isset($db_error)): ?>
                <div class="alert alert-danger">
                    <p><?php echo htmlspecialchars($db_error); ?></p>
                    <p>No seu terminal, por favor, execute: <code>php db/migrate.php</code></p>
                </div>
            <?php endif; ?>

            <?php if ($message): ?>
                <div class="alert alert-<?php echo htmlspecialchars($message_type); ?> alert-dismissible fade show" role="alert">
                    <?php echo htmlspecialchars($message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h3 mb-0 text-gray-800"><?php echo $page_title; ?></h1>
                <a href="add_installation.php" class="btn btn-primary">
                    <i class="bi bi-plus-circle-fill me-2"></i>Registrar Nova Instalação
                </a>
            </div>

            <div class="row">
                <div class="col-xl-3 col-md-6 mb-4">
                    <a href="index.php" class="kpi-link">
                        <div class="kpi-card card">
                            <div class="card-body">
                                <div class="kpi-icon" style="background-color: #4e73df;">
                                    <i class="bi bi-ev-station"></i>
                                </div>
                                <div>
                                    <div class="kpi-value"><?php echo $total_installations; ?></div>
                                    <div class="kpi-label">Total de Instalações</div>
                                </div>
                            </div>
                        </div>
                    </a>
                </div>
                 <div class="col-xl-3 col-md-6 mb-4">
                    <a href="index.php?status=ativo" class="kpi-link">
                        <div class="kpi-card card">
                            <div class="card-body">
                                <div class="kpi-icon" style="background-color: #1cc88a;">
                                    <i class="bi bi-check-circle"></i>
                                </div>
                                <div>
                                    <div class="kpi-value"><?php echo $active_installations; ?></div>
                                    <div class="kpi-label">Ativas</div>
                                </div>
                            </div>
                        </div>
                    </a>
                </div>
                 <div class="col-xl-3 col-md-6 mb-4">
                     <div class="kpi-card card">
                        <div class="card-body">
                            <div class="kpi-icon" style="background-color: #36b9cc;">
                                <i class="bi bi-person-check"></i>
                            </div>
                            <div>
                                <div class="kpi-value">0</div>
                                <div class="kpi-label">Técnicos</div>
                            </div>
                        </div>
                    </div>
                </div>
                 <div class="col-xl-3 col-md-6 mb-4">
                    <a href="index.php?status=Manutencao" class="kpi-link">
                        <div class="kpi-card card">
                            <div class="card-body">
                                <div class="kpi-icon" style="background-color: #f6c23e;">
                                    <i class="bi bi-tools"></i>
                                </div>
                                <div>
                                    <div class="kpi-value"><?php echo $maintenance_installations; ?></div>
                                    <div class="kpi-label">Manutenções</div>
                                </div>
                            </div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-3 col-md-6 mb-4">
                    <a href="index.php?status=Manutencao+Parcial" class="kpi-link">
                        <div class="kpi-card card">
                            <div class="card-body">
                                <div class="kpi-icon" style="background-color: #fd7e14;">
                                    <i class="bi bi-exclamation-triangle-fill"></i>
                                </div>
                                <div>
                                    <div class="kpi-value"><?php echo $partial_maintenance_installations; ?></div>
                                    <div class="kpi-label">Manutenção Parcial</div>
                                </div>
                            </div>
                        </div>
                    </a>
                </div>
            </div>

            <div class="card">
                 <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0"><i class="bi bi-list-task me-2"></i>Instalações Recentes</h5>
                    <a href="index.php" class="btn btn-sm btn-outline-secondary">Ver Todas</a>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Imagem</th>
                                    <th>Cliente</th>
                                    <th>Endereço</th>
                                    <th>Técnico</th>
                                    <th>Status</th>
                                    <th>Data</th>
                                    <th>Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($installations) && !isset($db_error)): ?>
                                    <tr>
                                        <td colspan="7" class="text-center">Nenhuma instalação encontrada para este status.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($installations as $inst): ?>
                                        <?php
                                        $first_image = $inst['first_image'];
                                        $status = $inst['status'] ?? 'desconhecido';
                                        $status_badge_class = 'bg-secondary'; // Default
                                        if ($status == 'ativo') {
                                            $status_badge_class = 'bg-success';
                                        } elseif ($status == 'Manutencao') {
                                            $status_badge_class = 'bg-warning';
                                        } elseif ($status == 'Manutenção Parcial') {
                                            $status_badge_class = 'bg-info';
                                        }
                                        ?>
                                        <tr>
                                            <td>
                                                <?php if ($first_image): ?>
                                                    <a href="<?php echo htmlspecialchars($first_image); ?>" target="_blank">
                                                        <img src="<?php echo htmlspecialchars($first_image); ?>" alt="Imagem da Instalação" style="width: 50px; height: 50px; object-fit: cover;">
                                                    </a>
                                                <?php else: ?>
                                                    N/A
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($inst['client_name'] ?: 'N/A'); ?></td>
                                            <td><?php echo htmlspecialchars($inst['address'] ?: 'N/A'); ?></td>
                                            <td><?php echo htmlspecialchars($inst['technician_name'] ?: 'N/A'); ?></td>
                                            <td><span class="badge <?php echo $status_badge_class; ?>"><?php echo ucfirst(htmlspecialchars($status)); ?></span></td>
                                                                                        <td>
                                                <?php 
                                                $display_date = !empty($inst['installation_date']) ? $inst['installation_date'] : $inst['created_at'];
                                                echo date("d/m/Y", strtotime($display_date)); 
                                                ?>
                                            </td>
                                            <td>
                                                <div class="btn-group">
                                                    <a href="view_installation.php?id=<?php echo $inst['id']; ?>" class="btn btn-sm btn-outline-primary" title="Visualizar"><i class="bi bi-eye-fill"></i></a>
                                                    <a href="edit_installation.php?id=<?php echo $inst['id']; ?>" class="btn btn-sm btn-outline-secondary" title="Editar"><i class="bi bi-pencil-fill"></i></a>
                                                    <a href="delete_installation.php?id=<?php echo $inst['id']; ?>" class="btn btn-sm btn-outline-danger" title="Excluir"><i class="bi bi-trash-fill"></i></a>
                                                    <a href="export_html.php?id=<?php echo $inst['id']; ?>" class="btn btn-sm btn-outline-success" title="Exportar para Word"><i class="bi bi-file-earmark-word-fill"></i></a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
