<?php
session_start();
require_once 'config.php';
require_once 'functions.php';
requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

$msg = ''; $error = '';

// Créer la table des règles
// Créer ou migrer la table gage_rules
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS gage_rules (
        id INT AUTO_INCREMENT PRIMARY KEY,
        phase VARCHAR(30) NOT NULL,
        role VARCHAR(30) NOT NULL,
        action VARCHAR(50) NOT NULL,
        allowed TINYINT(1) DEFAULT 0,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uniq_rule (phase,role,action)
    )");
    // Si la table existait avec ENUM, migrer vers VARCHAR
    $pdo->exec("ALTER TABLE gage_rules MODIFY COLUMN phase VARCHAR(30) NOT NULL");
    $pdo->exec("ALTER TABLE gage_rules MODIFY COLUMN role VARCHAR(30) NOT NULL");
    $pdo->exec("ALTER TABLE gage_rules MODIFY COLUMN action VARCHAR(50) NOT NULL");
} catch(Exception $e) {}

// Valeurs par défaut (selon votre document)
$defaults = [
    // PENDING TO ACCEPT
    'pending_accept' => [
        'gageur1'     => ['voir'=>1,'edit'=>1,'vote'=>0,'add_media'=>1,'afficher_media'=>1,'honor'=>0,'afficher_honor'=>0,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>0,'afficher_report'=>0],
        'gageur2'     => ['voir'=>1,'edit'=>0,'vote'=>0,'add_media'=>0,'afficher_media'=>0,'honor'=>0,'afficher_honor'=>0,'voir_media'=>0,'afficher_voir_media'=>0,'report'=>1,'afficher_report'=>1],
        'oracle'      => ['voir'=>0,'edit'=>1,'vote'=>0,'add_media'=>0,'afficher_media'=>0,'honor'=>0,'afficher_honor'=>0,'voir_media'=>0,'afficher_voir_media'=>0,'report'=>0,'afficher_report'=>0],
        'admin'       => ['voir'=>1,'edit'=>1,'vote'=>0,'add_media'=>1,'afficher_media'=>1,'honor'=>0,'afficher_honor'=>0,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>1,'afficher_report'=>1],
        'observation' => ['voir'=>0,'edit'=>0,'vote'=>0,'add_media'=>0,'afficher_media'=>0,'honor'=>0,'afficher_honor'=>0,'voir_media'=>0,'afficher_voir_media'=>0,'report'=>0,'afficher_report'=>0],
    ],
    // PENDING APRÈS ACCEPTATION
    'pending_after' => [
        'gageur1'     => ['voir'=>1,'edit'=>0,'vote'=>1,'add_media'=>1,'afficher_media'=>1,'honor'=>0,'afficher_honor'=>0,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>0,'afficher_report'=>0],
        'gageur2'     => ['voir'=>1,'edit'=>0,'vote'=>1,'add_media'=>0,'afficher_media'=>1,'honor'=>0,'afficher_honor'=>0,'voir_media'=>0,'afficher_voir_media'=>1,'report'=>1,'afficher_report'=>1],
        'oracle'      => ['voir'=>1,'edit'=>0,'vote'=>1,'add_media'=>0,'afficher_media'=>1,'honor'=>0,'afficher_honor'=>0,'voir_media'=>0,'afficher_voir_media'=>1,'report'=>1,'afficher_report'=>1],
        'admin'       => ['voir'=>1,'edit'=>1,'vote'=>1,'add_media'=>1,'afficher_media'=>1,'honor'=>0,'afficher_honor'=>0,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>1,'afficher_report'=>1],
        'observation' => ['voir'=>1,'edit'=>0,'vote'=>1,'add_media'=>0,'afficher_media'=>0,'honor'=>0,'afficher_honor'=>0,'voir_media'=>0,'afficher_voir_media'=>1,'report'=>0,'afficher_report'=>1],
    ],
    // WON/LOST
    'won_lost' => [
        'gageur1'     => ['voir'=>1,'edit'=>0,'vote'=>0,'add_media'=>1,'afficher_media'=>1,'honor'=>1,'afficher_honor'=>1,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>0,'afficher_report'=>0],
        'gageur2'     => ['voir'=>1,'edit'=>0,'vote'=>0,'add_media'=>1,'afficher_media'=>1,'honor'=>1,'afficher_honor'=>1,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>1,'afficher_report'=>1],
        'oracle'      => ['voir'=>1,'edit'=>0,'vote'=>0,'add_media'=>1,'afficher_media'=>1,'honor'=>1,'afficher_honor'=>1,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>1,'afficher_report'=>1],
        'admin'       => ['voir'=>1,'edit'=>1,'vote'=>0,'add_media'=>1,'afficher_media'=>1,'honor'=>1,'afficher_honor'=>1,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>1,'afficher_report'=>1],
        'observation' => ['voir'=>1,'edit'=>0,'vote'=>0,'add_media'=>0,'afficher_media'=>0,'honor'=>0,'afficher_honor'=>0,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>1,'afficher_report'=>1],
    ],
    // CLOSED
    'closed' => [
        'gageur1'     => ['voir'=>1,'edit'=>0,'vote'=>0,'add_media'=>0,'afficher_media'=>1,'honor'=>0,'afficher_honor'=>0,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>0,'afficher_report'=>0],
        'gageur2'     => ['voir'=>1,'edit'=>0,'vote'=>0,'add_media'=>0,'afficher_media'=>1,'honor'=>0,'afficher_honor'=>0,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>1,'afficher_report'=>1],
        'oracle'      => ['voir'=>1,'edit'=>0,'vote'=>0,'add_media'=>1,'afficher_media'=>1,'honor'=>0,'afficher_honor'=>0,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>1,'afficher_report'=>1],
        'admin'       => ['voir'=>1,'edit'=>1,'vote'=>0,'add_media'=>1,'afficher_media'=>1,'honor'=>0,'afficher_honor'=>0,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>1,'afficher_report'=>1],
        'observation' => ['voir'=>1,'edit'=>0,'vote'=>0,'add_media'=>0,'afficher_media'=>0,'honor'=>0,'afficher_honor'=>0,'voir_media'=>1,'afficher_voir_media'=>1,'report'=>1,'afficher_report'=>1],
    ],
];

// Insérer les défauts si la table est vide
// Toujours s'assurer que toutes les règles existent
// Toujours vérifier et insérer les règles manquantes
$count = (int)$pdo->query("SELECT COUNT(*) FROM gage_rules")->fetchColumn();
$expectedCount = 4 * 5 * 11; // 4 phases × 5 rôles × 11 actions
if (true) { // Toujours synchroniser
    foreach ($defaults as $phase => $roles) {
        foreach ($roles as $role => $actions) {
            foreach ($actions as $action => $val) {
                $pdo->prepare("REPLACE INTO gage_rules (phase,role,action,allowed) VALUES (?,?,?,?)")
                    ->execute([$phase,$role,$action,$val]);
            }
        }
    }
    $msg = "Règles initialisées avec les valeurs par défaut.";
}

// Sauvegarder une règle (AJAX)
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_rule'])) {
    header('Content-Type: application/json');
    $phase   = $_POST['phase']   ?? '';
    $role    = $_POST['role']    ?? '';
    $action  = $_POST['action']  ?? '';
    $allowed = (int)($_POST['allowed'] ?? 0);
    $valid_phases  = ['pending_accept','pending_after','won_lost','closed'];
    $valid_roles   = ['gageur1','gageur2','oracle','admin','observation'];
    $valid_actions = array_keys($defaults['closed']['admin']);
    if (in_array($phase,$valid_phases) && in_array($role,$valid_roles) && in_array($action,$valid_actions)) {
        $pdo->prepare("REPLACE INTO gage_rules (phase,role,action,allowed) VALUES (?,?,?,?)")
            ->execute([$phase,$role,$action,$allowed]);
        echo json_encode(['ok'=>true]);
    } else {
        echo json_encode(['error'=>'Valeurs invalides']);
    }
    exit;
}

// Réinitialiser toutes les règles
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['reset_rules'])) {
    try {
        $pdo->exec("DELETE FROM gage_rules");
        foreach ($defaults as $phase => $roles) {
            foreach ($roles as $role => $actions) {
                foreach ($actions as $action => $val) {
                    $pdo->prepare("REPLACE INTO gage_rules (phase,role,action,allowed) VALUES (?,?,?,?)")
                        ->execute([$phase,$role,$action,$val]);
                }
            }
        }
        $msg = "Règles réinitialisées aux valeurs par défaut.";
    } catch(Exception $e) { $error = $e->getMessage(); }
}

// Sauvegarder config expiration
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_expiry'])) {
    $days = max(1, (int)($_POST['expiry_days'] ?? 7));
    $enabled = (int)($_POST['expiry_enabled'] ?? 0);
    $pdo->prepare("INSERT INTO admin_config (config_key,config_value) VALUES ('gage_expiry_enabled',?) ON DUPLICATE KEY UPDATE config_value=?")->execute([$enabled,$enabled]);
    $pdo->prepare("INSERT INTO admin_config (config_key,config_value) VALUES ('gage_expiry_days',?) ON DUPLICATE KEY UPDATE config_value=?")->execute([$days,$days]);
    $msg = "Configuration expiration sauvegardée.";
}

// Charger les règles actuelles
$rulesData = [];
$rows = $pdo->query("SELECT * FROM gage_rules")->fetchAll();
foreach ($rows as $r) {
    $rulesData[$r['phase']][$r['role']][$r['action']] = (int)$r['allowed'];
}
// Merger avec les défauts pour les valeurs manquantes
foreach ($defaults as $phase => $roles) {
    foreach ($roles as $role => $actions) {
        foreach ($actions as $action => $val) {
            if (!isset($rulesData[$phase][$role][$action])) {
                $rulesData[$phase][$role][$action] = $val;
            }
        }
    }
}

// Config expiration
$expiryEnabled = (int)($cfgVals['gage_expiry_enabled'] ?? 0);
$expiryDays    = (int)($cfgVals['gage_expiry_days'] ?? 7);
try {
    $ec = $pdo->query("SELECT config_key,config_value FROM admin_config WHERE config_key LIKE 'gage_expiry%'")->fetchAll();
    foreach ($ec as $r) {
        if ($r['config_key']==='gage_expiry_enabled') $expiryEnabled = (int)$r['config_value'];
        if ($r['config_key']==='gage_expiry_days')    $expiryDays    = (int)$r['config_value'];
    }
} catch(Exception $e) {}

$phaseLabels  = ['pending_accept'=>'En attente d\'acceptation','pending_after'=>'Accepté (en cours)','won_lost'=>'Won / Lost','closed'=>'Closed'];
$roleLabels   = ['gageur1'=>'Gageur 1','gageur2'=>'Gageur 2','oracle'=>'Oracle','admin'=>'Admin','observation'=>'Observateur'];
$actionLabels = [
    'voir'=>'Voir le gage','edit'=>'Modifier','vote'=>'Voter',
    'add_media'=>'Ajouter média','afficher_media'=>'Voir bouton Ajouter',
    'honor'=>'Honorer/Non-honoré','afficher_honor'=>'Voir bouton Honorer',
    'voir_media'=>'Voir les médias','afficher_voir_media'=>'Voir bouton Médias',
    'report'=>'Signaler','afficher_report'=>'Voir bouton Signaler',
];
$actionGroups = [
    'Visibilité' => ['voir','edit','vote'],
    'Médias'     => ['add_media','afficher_media','voir_media','afficher_voir_media'],
    'Honoration' => ['honor','afficher_honor'],
    'Signalement'=> ['report','afficher_report'],
];

include 'header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
.rule-table { width:100%; border-collapse:collapse; font-size:0.7rem; }
.rule-table th { background:#050520; color:#888; font-weight:600; letter-spacing:0.5px; padding:6px 8px; border:1px solid #1a1a2a; text-align:center; }
.rule-table th.role-header { color:#0dcaf0; }
.rule-table td { border:1px solid #1a1a2a; padding:4px 6px; text-align:center; }
.rule-table tr:hover td { background:rgba(255,255,255,0.02); }
.rule-toggle { width:22px; height:22px; border-radius:4px; border:1px solid #333; cursor:pointer; display:inline-flex; align-items:center; justify-content:center; font-size:0.7rem; transition:all 0.15s; }
.rule-toggle.on  { background:rgba(40,167,69,0.2); border-color:#28a745; color:#28a745; }
.rule-toggle.off { background:rgba(220,53,69,0.1); border-color:#444; color:#555; }
.action-label { text-align:left !important; font-size:0.65rem; color:#aaa; padding-left:8px !important; white-space:nowrap; }
.phase-card { margin-bottom:24px; }
.group-header td { background:#0a0a14; color:#888; font-style:italic; font-size:0.6rem; text-align:left !important; padding:3px 8px; letter-spacing:0.5px; }
</style>

<div class="container-fluid mt-3 mb-5" style="max-width:1100px;">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="admin.php" class="btn btn-outline-secondary btn-sm"><i class="fa fa-arrow-left fa-xs me-1"></i>Admin</a>
        <h4 class="oracle-text text-info mb-0" style="letter-spacing:2px;"><i class="fa fa-gavel me-2"></i>RÈGLES DES GAGES</h4>
    </div>

    <?php if ($msg): ?><div class="alert alert-success py-2 small"><?= htmlspecialchars($msg) ?></div><?php endif; ?>

    <div class="d-flex align-items-center gap-3 mb-3 flex-wrap">
        <div class="alert py-2 mb-0 flex-grow-1" style="background:rgba(13,202,240,0.06);border:1px solid #0dcaf0;font-size:0.68rem;color:#0dcaf0;">
            <i class="fa fa-circle-info me-1"></i>
            Cliquez sur un carré pour activer/désactiver. Sauvegarde instantanée.
            <span style="color:#28a745;margin-left:12px;">■ Autorisé</span>
            <span style="color:#555;margin-left:8px;">■ Interdit</span>
        </div>
        <form method="POST">
            <button type="submit" name="reset_rules" class="btn btn-outline-danger btn-sm" style="font-size:0.65rem;"
                onclick="return confirm('Réinitialiser toutes les règles aux valeurs par défaut ?')">
                <i class="fa fa-rotate-left me-1"></i>Réinitialiser
            </button>
        </form>
    </div>

    <!-- Config expiration -->
    <div class="card bg-dark border-warning shadow mb-4">
        <div class="card-header py-2 fw-bold small" style="background:#1a1200;color:#ffc107;letter-spacing:1px;">
            <i class="fa fa-clock me-2"></i>EXPIRATION AUTOMATIQUE (Won/Lost sans action)
        </div>
        <div class="card-body">
            <form method="POST" class="d-flex gap-3 align-items-end flex-wrap">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="expiry_enabled" id="expiryEnabled" value="1" <?= $expiryEnabled?'checked':'' ?>>
                    <label class="form-check-label small text-muted" for="expiryEnabled">Activer l'expiration</label>
                </div>
                <div>
                    <label class="small text-muted d-block mb-1" style="font-size:0.62rem;">DÉLAI (jours)</label>
                    <input type="number" name="expiry_days" min="1" max="365" value="<?= $expiryDays ?>"
                           class="form-control form-control-sm bg-dark text-white border-secondary" style="width:80px;">
                </div>
                <button type="submit" name="save_expiry" class="btn btn-warning btn-sm fw-bold text-dark">
                    <i class="fa fa-floppy-disk me-1"></i>Sauvegarder
                </button>
            </form>
            <div class="text-muted mt-2" style="font-size:0.62rem;">
                Si les gageurs et l'Oracle n'ont pris aucune action <?= $expiryDays ?> jour(s) après que le gage est en Won/Lost, le statut passe automatiquement à "Non déterminé". À brancher dans le cron.
            </div>
        </div>
    </div>

    <!-- Matrices par phase -->
    <?php foreach ($phaseLabels as $phase => $phaseLabel): ?>
    <div class="phase-card">
        <div class="card bg-dark border-secondary shadow">
            <div class="card-header py-2" style="background:#050510;border-bottom:2px solid #0dcaf0;">
                <span class="fw-bold text-info" style="font-size:0.78rem;letter-spacing:1px;"><?= htmlspecialchars($phaseLabel) ?></span>
            </div>
            <div class="card-body p-2" style="overflow-x:auto;">
                <table class="rule-table">
                    <thead>
                        <tr>
                            <th style="width:160px;text-align:left;">Action</th>
                            <?php foreach ($roleLabels as $role => $roleLabel): ?>
                            <th class="role-header"><?= htmlspecialchars($roleLabel) ?></th>
                            <?php endforeach; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($actionGroups as $grpLabel => $actions): ?>
                        <tr class="group-header">
                            <td colspan="<?= count($roleLabels)+1 ?>"><?= htmlspecialchars($grpLabel) ?></td>
                        </tr>
                        <?php foreach ($actions as $action): ?>
                        <tr>
                            <td class="action-label"><?= htmlspecialchars($actionLabels[$action] ?? $action) ?></td>
                            <?php foreach (array_keys($roleLabels) as $role): ?>
                            <?php $val = $rulesData[$phase][$role][$action] ?? 0; ?>
                            <td>
                                <div class="rule-toggle <?= $val?'on':'off' ?>"
                                     data-phase="<?= $phase ?>"
                                     data-role="<?= $role ?>"
                                     data-action="<?= $action ?>"
                                     data-val="<?= $val ?>"
                                     onclick="toggleRule(this)"
                                     title="<?= $val?'Autorisé — cliquer pour interdire':'Interdit — cliquer pour autoriser' ?>">
                                    <?= $val ? '✓' : '' ?>
                                </div>
                            </td>
                            <?php endforeach; ?>
                        </tr>
                        <?php endforeach; ?>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<script>
function toggleRule(el) {
    const phase  = el.dataset.phase;
    const role   = el.dataset.role;
    const action = el.dataset.action;
    const newVal = el.dataset.val === '1' ? 0 : 1;

    fetch('admin_gage_rules.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'save_rule=1&phase='+encodeURIComponent(phase)+'&role='+encodeURIComponent(role)+'&action='+encodeURIComponent(action)+'&allowed='+newVal
    })
    .then(r => r.json())
    .then(d => {
        if (d.ok) {
            el.dataset.val  = newVal;
            el.className    = 'rule-toggle ' + (newVal ? 'on' : 'off');
            el.textContent  = newVal ? '✓' : '';
            el.title        = newVal ? 'Autorisé — cliquer pour interdire' : 'Interdit — cliquer pour autoriser';
        }
    });
}
</script>

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