<?php
// Fichier: admin_company_details.php
require 'includes/db.php';
require 'includes/auth.php';
require_login();

if ($_SESSION['user_role'] !== 'SUPER_ADMIN') { die("Accès interdit."); }

$id_cse = isset($_GET['id']) ? intval($_GET['id']) : 0;
$msg = "";

// 1. Mise à jour des infos de contact
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'update_contact') {
    $nom_contact = trim($_POST['nom_contact']);
    $tel_contact = trim($_POST['telephone_contact']);
    $email_contact = trim($_POST['email_contact']);
    
    $stmt = $pdo->prepare("UPDATE entreprises SET nom_contact=?, telephone_contact=?, email_contact=?, pourcentage_cagnotte=? WHERE id=?"); $stmt->execute([$nom_contact, $tel_contact, $email_contact, floatval($_POST['pourcentage_cagnotte']), $id_cse]);
}

// 2. Récupération des infos du CSE
$stmt = $pdo->prepare("SELECT * FROM entreprises WHERE id = ?");
$stmt->execute([$id_cse]);
$cse = $stmt->fetch();

if (!$cse) { die("CSE introuvable."); }

// 3. Récupération de l'historique complet des commandes
// Astuce SQL : GROUP_CONCAT pour mettre tous les produits d'une commande dans une seule case
$sql = "
    SELECT 
        c.id, c.reference, c.date_creation, c.total_ttc, c.statut,
        b.nom as nom_benef, b.prenom as prenom_benef,
        camp.nom as nom_campagne,
        GROUP_CONCAT(lc.quantite || 'x ' || lc.nom_produit_historique, ', ') as details_produits
    FROM commandes c
    JOIN beneficiaires b ON c.beneficiaire_id = b.id
    LEFT JOIN campagnes camp ON c.campagne_id = camp.id
    LEFT JOIN lignes_commande lc ON c.id = lc.commande_id
    WHERE b.entreprise_id = ?
    GROUP BY c.id
    ORDER BY c.date_creation DESC
";
$stmtHist = $pdo->prepare($sql);
$stmtHist->execute([$id_cse]);
$historique = $stmtHist->fetchAll();

// Calcul du CA Total à vie
$ca_total = 0;
foreach($historique as $h) { $ca_total += $h['total_ttc']; }

?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fiche CSE - <?= htmlspecialchars($cse['nom']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>

    <nav class="navbar navbar-dark bg-danger mb-4">
        <div class="container-fluid px-4">
            <span class="navbar-brand mb-0 h1">Fiche Client : <?= htmlspecialchars($cse['nom']) ?></span>
            <a href="admin_companies.php" class="btn btn-outline-light btn-sm">Retour Liste</a>
        </div>
    </nav>

    <div class="container">
        <?= $msg ?>

        <div class="row">
            <div class="col-md-4">
                <div class="card shadow-sm mb-4">
                    <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
                        <span><i class="material-icons align-middle fs-6">badge</i> Identité & Contact</span>
                    </div>
                    <div class="card-body">
                        <form method="POST">
    <input type="hidden" name="action" value="update_contact">
    
    <div class="mb-2">
        <label class="fw-bold">Code Client</label>
        <input type="text" class="form-control-plaintext" value="<?= htmlspecialchars($cse['code_client']) ?>" readonly>
    </div>

    <div class="mb-3 p-2 bg-warning bg-opacity-10 border border-warning rounded">
    <label class="fw-bold text-dark">Taux Cagnotte (%)</label>
    <div class="input-group">
        <input type="number" step="any" name="pourcentage_cagnotte" class="form-control fw-bold" 
               value="<?= floatval($cse['pourcentage_cagnotte']) ?>"> 
        <span class="input-group-text">%</span>
    </div>
</div>
    
    <hr>
    <h6 class="text-danger">Responsable / Secrétaire CSE</h6>
    
    <div class="mb-3">
        <label>Nom & Prénom</label>
        <input type="text" name="nom_contact" class="form-control" value="<?= htmlspecialchars($cse['nom_contact'] ?? '') ?>">
    </div>
    <div class="mb-3">
        <label>Email</label>
        <input type="email" name="email_contact" class="form-control" value="<?= htmlspecialchars($cse['email_contact'] ?? '') ?>">
    </div>
    <div class="mb-3">
        <label>Téléphone</label>
        <input type="text" name="telephone_contact" class="form-control" value="<?= htmlspecialchars($cse['telephone_contact'] ?? '') ?>">
    </div>

    <button type="submit" class="btn btn-gold btn-sm w-100">Enregistrer les modifications</button>
</form>
                    </div>
                </div>

                <div class="card shadow-sm bg-light mb-4">
                    <div class="card-body text-center">
                        <h6 class="text-muted">Chiffre d'Affaires Global</h6>
                        <h2 class="text-success fw-bold"><?= number_format($ca_total, 2, ',', ' ') ?> €</h2>
                        <small><?= count($historique) ?> commandes passées</small>
                    </div>
                </div>
            </div>

            <div class="col-md-8">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h4>Historique des Commandes</h4>
                    <div>
                        <a href="export_cse_csv.php?id=<?= $id_cse ?>" class="btn btn-success btn-sm">
                            <i class="material-icons align-middle" style="font-size:16px">file_download</i> Excel/CSV
                        </a>
                        <button onclick="window.print()" class="btn btn-secondary btn-sm">
                            <i class="material-icons align-middle" style="font-size:16px">print</i> Imprimer PDF
                        </button>
                    </div>
                </div>

                <div class="card shadow-sm">
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover mb-0" style="font-size: 0.9rem;">
                                <thead class="table-dark">
                                    <tr>
                                        <th>Date</th>
                                        <th>Référence</th>
                                        <th>Salarié</th>
                                        <th>Détail Produits</th>
                                        <th>Montant</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if(count($historique) == 0): ?>
                                        <tr><td colspan="5" class="text-center p-3">Aucune commande trouvée.</td></tr>
                                    <?php endif; ?>

                                    <?php foreach ($historique as $h): ?>
                                    <tr>
                                        <td><?= date('d/m/Y', strtotime($h['date_creation'])) ?></td>
                                        <td class="fw-bold"><?= htmlspecialchars($h['reference']) ?></td>
                                        <td>
                                            <?= htmlspecialchars($h['nom_benef'] . ' ' . $h['prenom_benef']) ?>
                                        </td>
                                        <td>
                                            <small class="text-muted"><?= htmlspecialchars($h['details_produits']) ?></small>
                                        </td>
                                        <td class="fw-bold text-end text-nowrap">
                                            <?= number_format($h['total_ttc'], 2, ',', ' ') ?> €
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <style>
        @media print {
            .navbar, .btn, form button { display: none !important; }
            .col-md-4 { display: none; } /* On cache la colonne de gauche à l'impression */
            .col-md-8 { width: 100% !important; flex: 0 0 100%; max-width: 100%; }
            body { background: white; }
            .card { border: none; shadow: none; }
        }
    </style>

</body>
</html>