<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

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

$userId = (int)$_SESSION['user_id'];
$betId  = (int)($_GET['bet_id'] ?? $_POST['bet_id'] ?? 0);
if (!$betId) { header("Location: index.php"); exit; }

// Charger le gage et les droits
$stmt = $pdo->prepare("SELECT b.*, u.tier FROM bets b JOIN users u ON u.id = ? WHERE b.id = ?");
$stmt->execute([$userId, $betId]);
$bet = $stmt->fetch();
if (!$bet) { header("Location: index.php"); exit; }

// Limites selon tier
$uStmt = $pdo->prepare("SELECT tier, admin FROM users WHERE id = ?");
$uStmt->execute([$userId]);
$uRow = $uStmt->fetch();
$tier     = $uRow['tier'] ?? 'free';
$isAdminU = (int)($uRow['admin'] ?? 0) === 1;

$photoLimit = 1;
if ($isAdminU || $tier === 'premium_plus') $photoLimit = 10;
elseif ($tier === 'premium')               $photoLimit = 5;

// Compter photos existantes
$cStmt = $pdo->prepare("SELECT COUNT(*) FROM bet_proofs WHERE bet_id = ?");
$cStmt->execute([$betId]);
$currentCount = (int)$cStmt->fetchColumn();

$error = '';
$success = '';

// Vérifier colonne file_type dans bet_proofs
try {
    $pdo->exec("ALTER TABLE bet_proofs ADD COLUMN IF NOT EXISTS file_type ENUM('photo','video') DEFAULT 'photo'");
} catch (Exception $e) {}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_FILES['photo']) || isset($_FILES['video']))) {

    // Vérifier limite photos selon le grade
    // Limite photos selon grade
    $tierKeyP = match($user['tier']??'free') {'premium_plus'=>'premplus','premium'=>'premium','admin'=>'admin',default=>'free'};
    $defP = match($tierKeyP){'admin'=>999,'premplus'=>30,'premium'=>10,default=>2};
    try { $rP=$pdo->prepare("SELECT config_value FROM admin_config WHERE config_key=?"); $rP->execute(['limit_photos_'.$tierKeyP]); $vP=$rP->fetchColumn(); $maxPhotos=(int)($vP!==false?$vP:$defP); } catch(Exception $e){ $maxPhotos=$defP; }
    $betIdP = (int)($_POST['bet_id']??0);
    if ($betIdP && !isAdmin($user)) {
        $nbP = (int)$pdo->query("SELECT nb_photos FROM bets WHERE id={$betIdP}")->fetchColumn();
        if ($nbP >= $maxPhotos) { http_response_code(400); echo json_encode(['error'=>"Limite de {$maxPhotos} photo(s) atteinte."]); exit; }
    }

    // Déterminer si c'est une photo ou vidéo
    $isVideo   = isset($_FILES['video']) && !empty($_FILES['video']['name']);
    $fileInput = $isVideo ? $_FILES['video'] : $_FILES['photo'];
    $fileType  = $isVideo ? 'video' : 'photo';

    // Vérifier accès vidéo (Premium+ ou Admin seulement)
    if ($isVideo && !$isAdminU && $tier !== 'premium_plus') {
        $error = "Les vidéos sont réservées aux membres Premium+.";
    } elseif ($currentCount >= $photoLimit) {
        $error = "Limite de {$photoLimit} fichier(s) atteinte pour ton forfait.";
    } else {
        $file = $fileInput;
        $ext  = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        if ($isVideo) {
            $allowed  = ['mp4','mov','avi','webm'];
            $maxSize  = 15 * 1024 * 1024; // 15 Mo
            $isValid  = in_array($ext, $allowed) && $file['size'] <= $maxSize;
            $errMsg   = !in_array($ext, $allowed) ? "Format vidéo non accepté (MP4, MOV, AVI, WEBM)." : "Vidéo trop grande (max 15 Mo).";
        } else {
            $allowed  = ['jpg','jpeg','png','gif','webp'];
            $maxSize  = 5 * 1024 * 1024; // 5 Mo
            $isValid  = in_array($ext, $allowed) && $file['size'] <= $maxSize && @getimagesize($file['tmp_name']);
            // Vérifier MIME réel (bloque les PHP renommés en .jpg)
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $realMime = finfo_file($finfo, $file['tmp_name']); finfo_close($finfo);
            $allowedMimes = ['image/jpeg','image/png','image/gif','image/webp'];
            if (!in_array($realMime, $allowedMimes)) $isValid = false;
            $errMsg   = !in_array($ext, $allowed) ? "Format non accepté (JPG, PNG, GIF, WEBP)." : ($file['size'] > $maxSize ? "Fichier trop grand (max 5 Mo)." : "Fichier invalide.");
        }

        if (!$isValid) {
            $error = $errMsg;
        } else {
            $dir = __DIR__ . '/uploads/proofs/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $filename = "bet_{$betId}_" . time() . "_" . rand(100,999) . ".{$ext}";
            if (move_uploaded_file($file['tmp_name'], $dir . $filename)) {
                $pdo->prepare("INSERT INTO bet_proofs (bet_id, file_path, file_type) VALUES (?, ?, ?)")
                    ->execute([$betId, 'uploads/proofs/' . $filename, $fileType]);
                $success = ($isVideo ? "Vidéo" : "Photo") . " ajoutée !";
                $currentCount++;
                addInteractionPoints($pdo, $userId, 'bet_view');
            } else {
                $error = "Erreur lors du transfert.";
            }
        }
    }
}

// Charger les photos existantes
$photos = $pdo->prepare("SELECT * FROM bet_proofs WHERE bet_id = ? ORDER BY id DESC");
$photos->execute([$betId]);
$photoList = $photos->fetchAll();

include 'header.php';
?>

<div class="container mt-4">
    <div class="row justify-content-center">
        <div class="col-md-7">
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                    <span class="fw-bold small"> PREUVES — GAGE #<?= $betId ?></span>
                    <a href="index.php" class="btn btn-outline-light btn-sm py-0">← Retour</a>
                </div>
                <div class="card-body">
                    <p class="text-muted small mb-2"><?= htmlspecialchars($bet['description']) ?></p>

                    <?php if ($error):   echo "<div class='alert alert-danger small py-2'>{$error}</div>";   endif; ?>
                    <?php if ($success): echo "<div class='alert alert-success small py-2'>{$success}</div>"; endif; ?>

                    <?php if ($currentCount < $photoLimit): ?>
                    <div class="mb-3">
                        <!-- Onglets Photo / Vidéo -->
                        <div class="d-flex gap-2 mb-2">
                            <button type="button" id="tabPhoto" onclick="switchTab('photo')"
                                    class="btn btn-sm btn-info fw-bold">Photo</button>
                            <?php if ($isAdminU || $tier === 'premium_plus'): ?>
                            <button type="button" id="tabVideo" onclick="switchTab('video')"
                                    class="btn btn-sm btn-outline-warning">Video (Premium+)</button>
                            <?php endif; ?>
                        </div>

                        <!-- Upload Photo -->
                        <div id="panelPhoto">
                            <label class="small text-white fw-bold d-block mb-1">
                                Photo (<?= $currentCount ?>/<?= $photoLimit ?>)
                            </label>
                            <div class="input-group input-group-sm mb-2">
                                <input type="file" id="photoInput" class="form-control" accept="image/*"
                                       onchange="document.getElementById('uploadBtn').disabled=false;">
                                <button id="uploadBtn" onclick="uploadFile('photo')" class="btn btn-success fw-bold" disabled>ENVOYER</button>
                            </div>
                            <small style="color:#aaa;font-size:0.65rem;">Max 5 Mo — JPG, PNG, GIF, WEBP</small>
                        </div>

                        <!-- Upload Vidéo -->
                        <?php if ($isAdminU || $tier === 'premium_plus'): ?>
                        <div id="panelVideo" style="display:none;">
                            <label class="small text-white fw-bold d-block mb-1">
                                Video (<?= $currentCount ?>/<?= $photoLimit ?>)
                            </label>
                            <div class="input-group input-group-sm mb-2">
                                <input type="file" id="videoInput" class="form-control" accept="video/*"
                                       onchange="document.getElementById('uploadBtnV').disabled=false;">
                                <button id="uploadBtnV" onclick="uploadFile('video')" class="btn btn-warning fw-bold" disabled>ENVOYER</button>
                            </div>
                            <small style="color:#aaa;font-size:0.65rem;">Max 15 Mo — MP4, MOV, AVI, WEBM</small>
                        </div>
                        <?php endif; ?>

                        <!-- Progress bar -->
                        <div id="uploadProgressWrap" style="display:none;margin-top:6px;">
                            <div class="progress mb-1" style="height:8px;">
                                <div id="uploadProgressBar" class="progress-bar progress-bar-striped progress-bar-animated bg-success" style="width:0%;"></div>
                            </div>
                            <small id="uploadStatus" class="text-info" style="font-size:0.65rem;">Envoi en cours...</small>
                        </div>
                    </div>
                    <?php else: ?>
                        <div class="alert alert-warning small py-2">Limite de fichiers atteinte (<?= $photoLimit ?>).</div>
                    <?php endif; ?>

                    <?php if (!empty($photoList)): ?>
                    <div class="d-flex flex-wrap gap-2 mt-2">
                        <?php foreach ($photoList as $p):
                            $isVid = ($p['file_type'] ?? 'photo') === 'video';
                        ?>
                            <?php if ($isVid): ?>
                            <video src="<?= htmlspecialchars($p['file_path']) ?>"
                                   controls
                                   style="width:160px;height:100px;object-fit:cover;border-radius:4px;border:1px solid #555;">
                            </video>
                            <?php else: ?>
                            <img src="<?= htmlspecialchars($p['file_path']) ?>"
                                 class="rounded border border-secondary"
                                 style="width:80px;height:80px;object-fit:cover;cursor:pointer;"
                                 onclick="window.open('<?= htmlspecialchars($p['file_path']) ?>')">
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>

<script>
function switchTab(tab) {
    document.getElementById('panelPhoto').style.display = tab === 'photo' ? '' : 'none';
    const panelV = document.getElementById('panelVideo');
    if (panelV) panelV.style.display = tab === 'video' ? '' : 'none';
    document.getElementById('tabPhoto').className = 'btn btn-sm ' + (tab==='photo' ? 'btn-info' : 'btn-outline-info') + ' fw-bold';
    const tabV = document.getElementById('tabVideo');
    if (tabV) tabV.className = 'btn btn-sm ' + (tab==='video' ? 'btn-warning' : 'btn-outline-warning');
}

function uploadFile(type) {
    const input = document.getElementById(type === 'video' ? 'videoInput' : 'photoInput');
    if (!input || !input.files[0]) return;

    const fd = new FormData();
    fd.append(type, input.files[0]);
    fd.append('bet_id', <?= $betId ?>);

    const bar    = document.getElementById('uploadProgressBar');
    const wrap   = document.getElementById('uploadProgressWrap');
    const status = document.getElementById('uploadStatus');
    const btn    = document.getElementById(type === 'video' ? 'uploadBtnV' : 'uploadBtn');

    wrap.style.display = '';
    if (btn) btn.disabled = true;
    bar.style.width = '0%';
    status.innerText = 'Envoi en cours...';

    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'upload_photo.php');

    xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
            const pct = Math.round(e.loaded / e.total * 100);
            bar.style.width = pct + '%';
            status.innerText = pct + '%';
        }
    };

    xhr.onload = function() {
        bar.style.width = '100%';
        bar.classList.remove('progress-bar-animated');
        status.innerText = type === 'video' ? 'Vidéo envoyée !' : 'Photo envoyée !';
        setTimeout(() => location.reload(), 800);
    };

    xhr.onerror = function() {
        bar.classList.add('bg-danger');
        status.innerText = 'Erreur lors de l\'envoi.';
        if (btn) btn.disabled = false;
    };

    xhr.send(fd);
}
</script>
