<?php
session_start();
require 'db.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// --- Gestion changement Email ---
$msg_email = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_email'])) {
    $new_email = filter_input(INPUT_POST, 'new_email', FILTER_VALIDATE_EMAIL);
    if ($new_email) {
        $stmt = $pdo->prepare("UPDATE users SET email = ? WHERE id = ?");
        $stmt->execute([$new_email, $_SESSION['user_id']]);
        $msg_email = "<div style='color:var(--ok); margin-bottom:10px;'>Email mis à jour avec succès.</div>";
    } else {
        $msg_email = "<div style='color:#ff4757; margin-bottom:10px;'>Format d'email invalide.</div>";
    }
}

// --- Gestion Suppression Appareil ---
$msg_device = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_device'])) {
    $device_name = trim($_POST['device_name']);
    if (!empty($device_name)) {
        // On insère une demande de type 'support'
        $stmt = $pdo->prepare("INSERT INTO requests (user_id, type, category, title, details, status, created_at) VALUES (?, 'support', 'suppression_appareil', ?, '{}', 'en_attente', NOW())");
        $title = "Retrait appareil : " . $device_name;
        $stmt->execute([$_SESSION['user_id'], $title]);
        $msg_device = "<div style='color:var(--ok); margin-bottom:10px;'>Demande de suppression envoyée.</div>";
    } else {
        $msg_device = "<div style='color:#ff4757; margin-bottom:10px;'>Veuillez entrer un nom d'appareil.</div>";
    }
}

// Récupérer l'email actuel
$stmt_u = $pdo->prepare("SELECT email FROM users WHERE id = ?");
$stmt_u->execute([$_SESSION['user_id']]);
$current_user = $stmt_u->fetch();

// Calculer les jours restants
$exp_date = new DateTime($_SESSION['exp_date']);
$today = new DateTime();
$interval = $today->diff($exp_date);
$daysLeft = $interval->format('%r%a');

// --- Pagination ---
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 100;
$offset = ($page - 1) * $limit;

// --- Filtres et Tri ---
$filter = $_GET['filter'] ?? '';
$sort = $_GET['sort'] ?? 'date_desc';

$where_clauses = ["user_id = :user_id"];
$params = [':user_id' => $_SESSION['user_id']];

if ($filter === 'bug') {
    $where_clauses[] = "type = 'bug'";
} elseif ($filter === 'film') {
    $where_clauses[] = "type = 'ajout' AND category = 'film'";
} elseif ($filter === 'serie') {
    $where_clauses[] = "type = 'ajout' AND category = 'serie'";
}

$where_sql = "WHERE " . implode(' AND ', $where_clauses);

$order_sql = "ORDER BY created_at DESC";
if ($sort === 'date_asc') $order_sql = "ORDER BY created_at ASC";
if ($sort === 'alpha_asc') $order_sql = "ORDER BY title ASC";
if ($sort === 'alpha_desc') $order_sql = "ORDER BY title DESC";

// Total requests count for pagination
$total_stmt = $pdo->prepare("SELECT COUNT(*) FROM requests $where_sql");
$total_stmt->execute($params);
$total_requests = $total_stmt->fetchColumn();
$total_pages = ceil($total_requests / $limit);

// Récupérer les demandes de l'utilisateur avec pagination
$stmt = $pdo->prepare("SELECT * FROM requests $where_sql $order_sql LIMIT :limit OFFSET :offset");
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
foreach ($params as $key => $val) {
    $stmt->bindValue($key, $val);
}
$stmt->execute();
$requests = $stmt->fetchAll();

//
// --- Logic to sort requests ---
//
$ongoing_requests = [];
$archived_requests = [];
$not_available_requests = [];
$seven_days_ago = new DateTime('-7 days');

foreach ($requests as $request) {
    if ($request['status'] === 'pas_encore_dispo') {
        $not_available_requests[] = $request;
    } elseif (in_array($request['status'], ['traite', 'bug_regle', 'ajoute'])) {
        $archived_requests[] = $request;
    } else {
        $ongoing_requests[] = $request;
    }
}

//
// --- Function to display a table of requests ---
//
function display_requests_table($requests_array, $title) {
    echo "<h2>$title</h2>";
    echo '<div class="card" style="overflow-x:auto;">';

    if (count($requests_array) > 0) {
        echo '<table>';
        echo '<thead><tr><th>Date</th><th>Type</th><th>Titre / Chaîne</th><th>Statut</th></tr></thead>';
        echo '<tbody>';

        foreach($requests_array as $req) {
            $row_style = '';
            if ($req['status'] === 'en_cours_de_traitement') {
                $row_style = 'style="background:rgba(91, 140, 255, 0.25)"';
            } elseif (in_array($req['status'], ['ajoute', 'bug_regle', 'traite'])) {
                $row_style = 'style="background:rgba(54, 211, 153, 0.15)"';
            } elseif ($req['status'] === 'pas_encore_dispo') {
                $row_style = 'style="background:rgba(255, 209, 102, 0.15)"';
            }
            echo '<tr ' . $row_style . '>';
            echo '<td>' . date('d/m/Y', strtotime($req['created_at'])) . '</td>';
            echo '<td>' . ucfirst($req['type']) . ' (' . ucfirst($req['category']) . ')</td>';
            echo '<td>' . htmlspecialchars($req['title'] ?: 'N/A') . '</td>';
            echo '<td>';
            echo '<span class="status-badge status-' . $req['status'] . '">' . str_replace('_', ' ', ucfirst($req['status'])) . '</span>';
            if ($req['status'] === 'pas_encore_dispo') {
                echo '<div class="tooltip">ⓘ<span class="tooltiptext">Le film est trop récent ou n\'est pas encore disponible en bonne qualité et ou en Francais. Nous l\'ajouterons dès que possible.</span></div>';
            }
            echo '</td>';
            echo '</tr>';
        }

        echo '</tbody></table>';
    } else {
        echo '<p style="text-align:center; color:var(--muted)">Aucune demande dans cette catégorie.</p>';
    }

    echo '</div>';
}
?>
<!DOCTYPE html>
<html lang="fr" data-theme="system">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Espace Client – Streambox</title>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
  <style>
    /* === LIQUID GLASS THEME === */
    :root{ --bg:#0f172a; --glass:rgba(30, 41, 59, 0.65); --glass-border:rgba(255,255,255,0.08); --pri:#6366f1; --txt:#f1f5f9; --muted:#94a3b8; --ok:#10b981; --warn:#f59e0b; --radius:16px; }
    
    body{ 
        background:var(--bg); color:var(--txt); font-family:'Inter',sans-serif; margin:0; padding:20px; 
        background-image: 
            radial-gradient(circle at 10% 20%, rgba(99, 102, 241, 0.15), transparent 30%), 
            radial-gradient(circle at 90% 80%, rgba(168, 85, 247, 0.15), transparent 30%);
        background-attachment: fixed;
        min-height: 100vh;
    }
    
    .container{ max-width:1100px; margin:0 auto; position: relative; z-index: 1; }
    .header{ display:flex; justify-content:space-between; align-items:center; margin-bottom:40px; }
    
    .card{ 
        background:var(--glass); backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); 
        border:1px solid var(--glass-border); border-radius:var(--radius); padding:24px; margin-bottom:24px; 
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2); animation: slideUp 0.6s cubic-bezier(0.16, 1, 0.3, 1);
    }
    @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
    
    .stat-grid{ display:grid; grid-template-columns:repeat(auto-fit, minmax(200px, 1fr)); gap:20px; margin-bottom:30px; }
    .btn{ background:var(--pri); color:white; padding:10px 20px; text-decoration:none; border-radius:10px; font-weight:bold; display:inline-block; transition: all 0.2s; box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3); border: none; cursor: pointer; }
    .btn:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(99, 102, 241, 0.4); }
    
    table { width: 100%; border-collapse: separate; border-spacing: 0 8px; }
    th { text-align: left; padding: 12px; color: var(--muted); font-size: 0.85em; text-transform: uppercase; letter-spacing: 1px; }
    td { padding: 16px; background: rgba(255,255,255,0.02); border-top: 1px solid var(--glass-border); border-bottom: 1px solid var(--glass-border); vertical-align: middle; }
    td:first-child { border-left: 1px solid var(--glass-border); border-radius: 12px 0 0 12px; }
    td:last-child { border-right: 1px solid var(--glass-border); border-radius: 0 12px 12px 0; }
    
    .status-badge { padding: 4px 8px; border-radius: 4px; font-size: 0.85em; font-weight: bold; }
    .status-en_attente { background: rgba(255, 209, 102, 0.15); color: var(--warn); }
    .status-demande_prise_en_charge { background: rgba(139, 92, 246, 0.15); color: #8B5CF6; }
    .status-en_cours_de_traitement { background: rgba(91, 140, 255, 0.15); color: var(--pri); }
    .status-bug_regle { background: rgba(22, 163, 74, 0.15); color: #16A34A; }
    .status-traite { background: rgba(54, 211, 153, 0.15); color: var(--ok); }
    .status-ajoute { background: rgba(22, 163, 74, 0.15); color: #16A34A; }
    .status-pas_encore_dispo { background: rgba(245, 158, 11, 0.15); color: #F59E0B; }

    /* Tooltip styles */
    .tooltip { position: relative; display: inline-block; cursor: pointer; margin-left: 8px; color: var(--pri); font-weight: bold; }
    .tooltip .tooltiptext { visibility: hidden; width: 220px; background-color: rgba(15, 23, 42, 0.95); color: #fff; text-align: center; border-radius: 6px; padding: 8px; position: absolute; z-index: 10; bottom: 135%; left: 50%; margin-left: -110px; opacity: 0; transition: opacity 0.3s; font-size: 0.85em; font-weight: normal; border: 1px solid var(--glass-border); box-shadow: 0 4px 15px rgba(0,0,0,0.3); backdrop-filter: blur(5px); }
    .tooltip:hover .tooltiptext { visibility: visible; opacity: 1; }

    .pagination { display: flex; justify-content: center; margin-top: 20px; gap: 5px; }
    .pagination a { color: var(--muted); padding: 8px 16px; text-decoration: none; border: 1px solid var(--glass-border); border-radius: 8px; transition: all 0.3s; background: rgba(255,255,255,0.03); }
    .pagination a:hover { background: rgba(255,255,255,0.1); color: var(--txt); }
    .pagination a.active { background: var(--pri); color: white; border-color: var(--pri); box-shadow: 0 4px 12px rgba(99, 102, 241, 0.4); }

    /* Modal styles */
    .modal {
      display: none; /* Hidden by default */
      position: fixed; /* Stay in place */
      z-index: 100; /* Sit on top */
      left: 0;
      top: 0;
      width: 100%; /* Full width */
      height: 100%; /* Full height */
      overflow: auto; /* Enable scroll if needed */
      background-color: rgba(0,0,0,0.6); /* Black w/ opacity */
      backdrop-filter: blur(5px);
      padding-top: 60px;
    }
    .modal-content {
      background-color: #1e293b;
      border: 1px solid var(--glass-border);
      margin: 5% auto;
      padding: 30px;
      border-radius: var(--radius);
      width: 90%;
      max-width: 500px;
      position: relative;
      text-align: center;
    }
    .close-btn {
      color: var(--muted);
      position: absolute;
      top: 15px;
      right: 25px;
      font-size: 28px;
      font-weight: bold;
    }
    .close-btn:hover,
    .close-btn:focus {
      color: var(--txt);
      text-decoration: none;
      cursor: pointer;
    }
    .social-logos {
        display: flex;
        justify-content: center;
        gap: 30px;
        margin: 20px 0;
    }
    .social-logos img {
        height: 60px;
    }
    .modal-note {
        font-size: 0.9em;
        color: var(--muted);
    }

    @media (max-width: 768px) {
      body {
        padding: 10px;
      }
      .card {
        padding: 15px;
      }
      .stat-grid {
        grid-template-columns: 1fr;
      }
      th, td {
        padding: 8px;
        font-size: 0.9em;
      }
      h1 {
        font-size: 1.5em;
      }
      /* Fix tooltip mobile */
      .tooltip .tooltiptext {
        width: 180px;
        left: auto;
        right: 0;
        margin-left: 0;
      }
    }

    .tabs { display: flex; gap: 12px; margin-bottom: 24px; border-bottom: 1px solid var(--glass-border); padding-bottom: 16px; overflow-x: auto; }
    .tab { padding: 10px 20px; border-radius: 12px; text-decoration: none; color: var(--muted); font-weight: 600; transition: all 0.3s; white-space: nowrap; background: rgba(255,255,255,0.03); }
    .tab:hover { background: rgba(255,255,255,0.08); color: var(--txt); transform: translateY(-2px); }
    .tab.active { background: var(--pri); color: white; box-shadow: 0 4px 12px rgba(99, 102, 241, 0.4); }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>Bonjour, <?= htmlspecialchars($_SESSION['username']) ?></h1>
      <a href="logout.php" class="btn" style="background:rgba(255,255,255,0.05); border:1px solid var(--glass-border);">Déconnexion</a>
    </div>

    <div class="stat-grid">
      <div class="card">
        <div style="color:var(--muted); margin-bottom:5px;">Abonnement</div>
        <div style="font-size:1.5em; font-weight:800;">
            <?= ($daysLeft > 0) ? $daysLeft . ' Jours restants' : 'Expiré' ?>
        </div>
        <div style="font-size:0.9em; margin-top:5px; opacity:0.7">Expire le : <?= date('d/m/Y', strtotime($_SESSION['exp_date'])) ?></div>
        <button id="renew-btn" class="btn" style="margin-top: 15px; width: 100%;">Renouveler</button>
        
        <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid var(--glass-border);">
            <div style="margin-bottom: 8px; display: flex; align-items: center;">
                <span style="color:var(--muted); font-size: 0.9em;">Mon mail de contact</span>
                <div class="tooltip">ⓘ<span class="tooltiptext">Ce mail sert à rester informé lors des mises à jour des demandes et des potentielles maintenances.</span></div>
            </div>
            <button id="email-btn" class="btn" style="width: 100%; background:rgba(255,255,255,0.05); border:1px solid var(--glass-border); font-size: 0.9em; display: flex; justify-content: space-between; align-items: center;">
                <span style="overflow: hidden; text-overflow: ellipsis;"><?= htmlspecialchars($current_user['email'] ?: 'Aucun email') ?></span>
                <span>✎</span>
            </button>
        </div>

        <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid var(--glass-border);">
            <div style="margin-bottom: 8px; display: flex; align-items: center;">
                <span style="color:var(--muted); font-size: 0.9em;">Mes appareils MaxPlayer</span>
            </div>
            <button id="device-btn" class="btn" style="width: 100%; background:rgba(255,255,255,0.05); border:1px solid var(--glass-border); font-size: 0.9em; display: flex; justify-content: space-between; align-items: center;">
                <span>Retirer un appareil</span>
                <span>🗑️</span>
            </button>
        </div>
      </div>
      <div class="card" style="display:flex; align-items:center; justify-content:space-between;">
        <div>
            <div style="color:var(--muted); margin-bottom:5px;">Besoin d'aide ?</div>
            <div style="font-weight:bold;">Signaler un bug ou demander un ajout</div>
        </div>
        <a href="signalement.php" class="btn">Nouvelle demande</a>
      </div>
    </div>

    <?= $msg_email ?>
    <?= $msg_device ?>

    <div class="tabs">
        <a href="?<?= http_build_query(array_merge($_GET, ['filter' => '', 'page' => 1])) ?>" class="tab <?= $filter === '' ? 'active' : '' ?>">Global</a>
        <a href="?<?= http_build_query(array_merge($_GET, ['filter' => 'film', 'page' => 1])) ?>" class="tab <?= $filter === 'film' ? 'active' : '' ?>">Films</a>
        <a href="?<?= http_build_query(array_merge($_GET, ['filter' => 'serie', 'page' => 1])) ?>" class="tab <?= $filter === 'serie' ? 'active' : '' ?>">Séries</a>
        <a href="?<?= http_build_query(array_merge($_GET, ['filter' => 'bug', 'page' => 1])) ?>" class="tab <?= $filter === 'bug' ? 'active' : '' ?>">Bugs</a>
    </div>

    <!-- Filtres et Tri -->
    <form method="GET" style="margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap;">
        <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
        <select name="sort" onchange="this.form.submit()" style="background:rgba(15, 23, 42, 0.6); color:var(--txt); border:1px solid var(--glass-border); padding:8px; border-radius:8px;">
            <option value="date_desc" <?= $sort === 'date_desc' ? 'selected' : '' ?>>Date (Récent)</option>
            <option value="date_asc" <?= $sort === 'date_asc' ? 'selected' : '' ?>>Date (Ancien)</option>
            <option value="alpha_asc" <?= $sort === 'alpha_asc' ? 'selected' : '' ?>>Alphabétique (A-Z)</option>
            <option value="alpha_desc" <?= $sort === 'alpha_desc' ? 'selected' : '' ?>>Alphabétique (Z-A)</option>
        </select>
    </form>

    <?php 
      display_requests_table($ongoing_requests, 'Mes demandes en cours');
      display_requests_table($not_available_requests, 'Pas encore disponible');
      display_requests_table($archived_requests, 'Historique de mes demandes');
    ?>

    <div class="pagination">
        <?php if ($page > 1): ?>
            <a href="?page=<?= $page - 1 ?>&filter=<?= htmlspecialchars($filter) ?>&sort=<?= htmlspecialchars($sort) ?>">Précédent</a>
        <?php endif; ?>

        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
            <a href="?page=<?= $i ?>&filter=<?= htmlspecialchars($filter) ?>&sort=<?= htmlspecialchars($sort) ?>" class="<?= $i == $page ? 'active' : '' ?>"><?= $i ?></a>
        <?php endfor; ?>

        <?php if ($page < $total_pages): ?>
            <a href="?page=<?= $page + 1 ?>&filter=<?= htmlspecialchars($filter) ?>&sort=<?= htmlspecialchars($sort) ?>">Suivant</a>
        <?php endif; ?>
    </div>
    
  </div>

  <!-- The Modal -->
  <div id="renew-modal" class="modal">
    <div class="modal-content">
      <span class="close-btn">&times;</span>
      <h2>Renouvellement</h2>
      <p>Contactez-nous via l'une des plateformes suivantes :</p>
      <div class="social-logos">
        <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/ad/Snapchat_logo.svg/1024px-Snapchat_logo.svg.png" alt="Snapchat Logo">
        <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/82/Telegram_logo.svg/240px-Telegram_logo.svg.png" alt="Telegram Logo">
      </div>
      <p class="modal-note">Si vous etes passez par notre numéro, envoyez nous un message directement dessus.</p>
    </div>
  </div>

  <!-- Modal Email -->
  <div id="email-modal" class="modal">
    <div class="modal-content">
      <span class="close-btn-email close-btn">&times;</span>
      <h2>Modifier mon email</h2>
      <form method="POST">
        <label style="display:block; text-align:left; margin-bottom:5px; color:var(--muted);">Nouvel Email</label>
        <input type="email" name="new_email" value="<?= htmlspecialchars($current_user['email'] ?? '') ?>" required style="width:100%; padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(15, 23, 42, 0.6); color:white; margin-bottom:15px; box-sizing:border-box;">
        <button type="submit" name="update_email" class="btn" style="width:100%;">Enregistrer</button>
      </form>
    </div>
  </div>

  <!-- Modal Device Removal -->
  <div id="device-modal" class="modal">
    <div class="modal-content">
      <span class="close-btn-device close-btn">&times;</span>
      <h2>Retirer un appareil</h2>
      <p class="modal-note" style="margin-bottom:15px;">Indiquez le nom de l'appareil à retirer de votre compte MaxPlayer.</p>
      <form method="POST">
        <input type="text" name="device_name" placeholder="Ex: TV Salon, iPhone de Paul..." required style="width:100%; padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(15, 23, 42, 0.6); color:white; margin-bottom:15px; box-sizing:border-box;">
        <button type="submit" name="remove_device" class="btn" style="width:100%;">Envoyer la demande</button>
      </form>
    </div>
  </div>

  <script>
    // Get the modal
    var modal = document.getElementById("renew-modal");

    // Get the button that opens the modal
    var btn = document.getElementById("renew-btn");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close-btn")[0];

    // When the user clicks the button, open the modal 
    btn.onclick = function() {
      modal.style.display = "block";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
      modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
      if (event.target == modal) {
        modal.style.display = "none";
      }
    }

    // --- Script Modal Email ---
    var modalEmail = document.getElementById("email-modal");
    var btnEmail = document.getElementById("email-btn");
    var spanEmail = document.getElementsByClassName("close-btn-email")[0];

    btnEmail.onclick = function() { modalEmail.style.display = "block"; }
    spanEmail.onclick = function() { modalEmail.style.display = "none"; }
    
    // --- Script Modal Device ---
    var modalDevice = document.getElementById("device-modal");
    var btnDevice = document.getElementById("device-btn");
    var spanDevice = document.getElementsByClassName("close-btn-device")[0];

    btnDevice.onclick = function() { modalDevice.style.display = "block"; }
    spanDevice.onclick = function() { modalDevice.style.display = "none"; }

    // Fermeture au clic en dehors (gère les deux modales)
    window.onclick = function(event) {
      if (event.target == modal) { modal.style.display = "none"; }
      if (event.target == modalEmail) { modalEmail.style.display = "none"; }
      if (event.target == modalDevice) { modalDevice.style.display = "none"; }
    }
  </script>
  <footer style="text-align: center; color: var(--muted); font-size: 0.9em; padding: 20px 0;">
    <p>Pour nous contacter : streamboxtv@protonmail.com</p>
  </footer>
</body>
</html>
