<?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)($_POST['bet_id'] ?? 0);
$action = $_POST['action_edit'] ?? '';

if (!$betId) { header("Location: index.php"); exit; }

// Charger le gage
$stmt = $pdo->prepare("SELECT * FROM bets WHERE id = ?");
$stmt->execute([$betId]);
$bet = $stmt->fetch();
if (!$bet) { header("Location: index.php"); exit; }

// Bloquer si gage verrouillé (accepté par les 2 parties)
if (!$isAdmin) {
    $locked = ($bet['acceptance_status'] === 'accepted')
        || ($bet['status'] === 'completed')
        || !empty($bet['honored']);
    if ($locked) { header("Location: index.php?error=gage_locked"); exit; }
}

// Vérifier droits
$uStmt = $pdo->prepare("SELECT admin FROM users WHERE id = ?");
$uStmt->execute([$userId]);
$uRow = $uStmt->fetch();
$isAdminU = (int)($uRow['admin'] ?? 0) === 1;
$isOwner  = (int)$bet['user_id'] === $userId;

if (!$isAdminU && !$isOwner) { header("Location: index.php"); exit; }

if ($action === 'delete') {
    // Effacer votes, preuves, puis le gage
    $pdo->prepare("DELETE FROM bet_votes  WHERE bet_id = ?")->execute([$betId]);
    $pdo->prepare("DELETE FROM bet_proofs WHERE bet_id = ?")->execute([$betId]);
    $pdo->prepare("DELETE FROM bets       WHERE id = ?")    ->execute([$betId]);
    header("Location: index.php");
    exit;
}

if ($action === 'save') {
    $desc      = htmlspecialchars(trim($_POST['description'] ?? ''));
    $amount    = max(1, min(50, (int)($_POST['amount'] ?? 1)));
    $status    = in_array($_POST['status'], ['pending','won','lost']) ? $_POST['status'] : 'pending';
    $parieur2  = !empty($_POST['parieur2']) ? (int)$_POST['parieur2'] : null;
    $echeance  = !empty($_POST['echeance']) ? $_POST['echeance'] : null;
    $cell      = htmlspecialchars($_POST['cellulaire'] ?? '');
    $courriel  = htmlspecialchars($_POST['courriel'] ?? '');
    $hidden    = isset($_POST['hidden']) ? 1 : 0;

    $upd = $pdo->prepare("UPDATE bets SET
        description = ?, amount = ?, status = ?, parieur2_id = ?,
        echeance = ?, cellulaire = ?, courriel = ?, hidden = ?
        WHERE id = ?");
    $upd->execute([$desc, $amount, $status, $parieur2, $echeance, $cell, $courriel, $hidden, $betId]);

    // Mettre à jour user_stats si statut changé par admin
    if ($isAdminU && in_array($status, ['won','lost'])) {
        $prev = $bet['status'];
        if ($prev === 'pending' && $status === 'won') {
            $pdo->prepare("UPDATE user_stats SET won_bets = won_bets+1, total_bets = total_bets+1 WHERE user_id=?")->execute([$bet['user_id']]);
            $pdo->prepare("UPDATE users SET points = points + ? WHERE id=?")->execute([$amount, $bet['user_id']]);
            addNotification($pdo, (int)$bet['user_id'], " Ton gage #{$betId} a été marqué GAGNÉ !", "index.php");
        } elseif ($prev === 'pending' && $status === 'lost') {
            $pdo->prepare("UPDATE user_stats SET lost_bets = lost_bets+1, total_bets = total_bets+1 WHERE user_id=?")->execute([$bet['user_id']]);
            addNotification($pdo, (int)$bet['user_id'], "❌ Ton gage #{$betId} a été marqué PERDU.", "index.php");
        }
    }
}

header("Location: index.php");
exit;
?>
