<?php
$pageTitle = 'Paramètres';
require_once __DIR__ . '/includes/header.php';
requireRole(['admin']);
$db = getDB();

$action = $_GET['action'] ?? '';

// === BACKUP: Download database file ===
if ($action === 'backup') {
    // Force SQLite to write WAL to main DB file before backup
    $db->exec('PRAGMA wal_checkpoint(TRUNCATE)');
    
    $dbPath = APP_ROOT . '/data/uptours.db';
    if (file_exists($dbPath)) {
        logAction($_SESSION['user_id'], 'backup', 'Sauvegarde de la base de données');
        
        $backupName = 'uptours_backup_' . date('Y-m-d_His') . '.db';
        if (ob_get_level()) ob_end_clean();
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $backupName . '"');
        header('Content-Length: ' . filesize($dbPath));
        readfile($dbPath);
        exit;
    }
    flash('error', 'Fichier de base de données introuvable.');
    redirect('/parametres.php');
}

// === RESET: Delete all data and re-seed ===
if ($action === 'reset' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $confirmCode = $_POST['confirm_code'] ?? '';
    if ($confirmCode !== 'REINITIALISER') {
        flash('error', 'Code de confirmation incorrect. Tapez exactement: REINITIALISER');
        redirect('/parametres.php');
    }

    try {
        // Disable foreign keys temporarily to avoid constraint errors during deletion
        $db->exec('PRAGMA foreign_keys=OFF');
        
        // Keep settings, drop and recreate everything else
        $tables = ['logs','documents','paiements','depenses','inscriptions','groupes','vols','hotels','programmes','voyageurs'];
        foreach ($tables as $t) {
            $db->exec("DELETE FROM $t");
            $db->exec("DELETE FROM sqlite_sequence WHERE name='$t'");
        }
        
        // Reset users except admin
        $db->exec("DELETE FROM users WHERE role != 'admin'");
        // Reset admin password to default
        $db->prepare("UPDATE users SET password=? WHERE username='admin'")
            ->execute([password_hash('admin123', PASSWORD_DEFAULT)]);
            
        $db->exec('PRAGMA foreign_keys=ON');

        logAction($_SESSION['user_id'], 'reset', 'Réinitialisation complète de la base de données');
        flash('success', 'Base de données réinitialisée avec succès. Le compte admin a été conservé (mot de passe: admin123).');
    } catch (Exception $e) {
        flash('error', 'Erreur lors de la réinitialisation : ' . $e->getMessage());
    }
    redirect('/parametres.php');
}

// === RESTORE: Upload a backup file ===
if ($action === 'restore' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_FILES['backup_file']['name'])) {
        $ext = strtolower(pathinfo($_FILES['backup_file']['name'], PATHINFO_EXTENSION));
        if ($ext !== 'db') {
            flash('error', 'Fichier invalide. Seuls les fichiers .db sont acceptés.');
            redirect('/parametres.php');
        }
        $dbPath = APP_ROOT . '/data/uptours.db';
        
        // Checkpoint existing DB before we overwrite it
        $db->exec('PRAGMA wal_checkpoint(TRUNCATE)');
        
        // Create a safety backup first
        $safetyBackup = APP_ROOT . '/data/uptours_before_restore_' . date('Y-m-d_His') . '.db';
        copy($dbPath, $safetyBackup);
        
        // Close the database connection to release file locks
        $db = null;
        Database::getInstance()->closeConnection();
        
        // Delete WAL and SHM files to prevent corruption with the new DB file
        @unlink($dbPath . '-wal');
        @unlink($dbPath . '-shm');
        
        // Replace the database
        if (move_uploaded_file($_FILES['backup_file']['tmp_name'], $dbPath)) {
            // Reconnect to the new database to log the action
            $db = Database::getInstance()->getConnection();
            logAction($_SESSION['user_id'], 'restore', 'Restauration de la base de données depuis un fichier');
            flash('success', 'Base de données restaurée avec succès. Une sauvegarde de sécurité a été créée.');
        } else {
            $db = Database::getInstance()->getConnection();
            flash('error', 'Erreur lors de la restauration. Vérifiez les permissions du dossier data.');
        }
    } else {
        flash('error', 'Veuillez sélectionner un fichier de sauvegarde.');
    }
    redirect('/parametres.php');
}

// === SAVE AGENCY SETTINGS ===
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$action) {
    $fields = [
        'agence_nom','agence_slogan','agence_adresse','agence_ville',
        'agence_telephone','agence_telephone2','agence_fax','agence_email','agence_site_web',
        'agence_ice','agence_if','agence_rc','agence_cnss','agence_patente','agence_licence',
        'agence_banque_nom','agence_banque_agence','agence_banque_rib','agence_banque_iban','agence_banque_swift',
    ];

    $stmt = $db->prepare("INSERT INTO settings (setting_key, setting_value, updated_at) VALUES (?, ?, datetime('now'))
        ON CONFLICT(setting_key) DO UPDATE SET setting_value=excluded.setting_value, updated_at=datetime('now')");

    foreach ($fields as $f) {
        $stmt->execute([$f, $_POST[$f] ?? '']);
    }

    // Handle logo upload
    if (!empty($_FILES['agence_logo']['name'])) {
        $logo = uploadFile($_FILES['agence_logo'], UPLOAD_DIR, ['jpg','jpeg','png','gif','svg','webp']);
        if ($logo) {
            // Delete old logo
            $oldLogo = getSetting('agence_logo');
            if ($oldLogo && file_exists(UPLOAD_DIR . $oldLogo)) {
                unlink(UPLOAD_DIR . $oldLogo);
            }
            $stmt->execute(['agence_logo', $logo]);
        }
    }

    logAction($_SESSION['user_id'], 'settings_update', 'Paramètres de l\'agence mis à jour');
    flash('success', 'Paramètres enregistrés avec succès.');
    redirect('/parametres.php');
}

// Load current settings
$settings = getAgencyInfo();
$s = function($key) use ($settings) { return sanitize($settings[$key] ?? ''); };

// DB stats
$dbPath = APP_ROOT . '/data/uptours.db';
$dbSize = file_exists($dbPath) ? filesize($dbPath) : 0;
$dbSizeFormatted = $dbSize > 1048576 ? round($dbSize/1048576, 2).' Mo' : round($dbSize/1024, 1).' Ko';
$tableStats = [];
foreach (['users','voyageurs','programmes','inscriptions','paiements','depenses','hotels','vols','groupes','documents','logs'] as $t) {
    $tableStats[$t] = $db->query("SELECT COUNT(*) FROM $t")->fetchColumn();
}
?>

<ul class="nav nav-tabs mb-4" role="tablist">
    <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tab-agence"><i class="bi bi-building me-1"></i>Agence</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-legal"><i class="bi bi-file-earmark-text me-1"></i>Juridique & Fiscal</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-banque"><i class="bi bi-bank me-1"></i>Coordonnées bancaires</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-donnees"><i class="bi bi-database me-1"></i>Données & Sauvegarde</a></li>
</ul>

<div class="tab-content">

    <!-- TAB: Agence -->
    <div class="tab-pane fade show active" id="tab-agence">
        <form method="POST" enctype="multipart/form-data">
        <div class="card table-card mb-4">
            <div class="card-header"><i class="bi bi-building me-2"></i>Informations de l'agence</div>
            <div class="card-body p-4">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label fw-bold">Logo de l'agence</label>
                        <div class="mb-2">
                            <?php if (!empty($settings['agence_logo'])): ?>
                                <img src="<?= APP_URL ?>/uploads/<?= $s('agence_logo') ?>" alt="Logo" class="img-thumbnail" style="max-height:80px;">
                            <?php else: ?>
                                <div class="border rounded p-3 text-center text-muted bg-light"><i class="bi bi-image fs-3"></i><br><small>Aucun logo</small></div>
                            <?php endif; ?>
                        </div>
                        <input type="file" name="agence_logo" class="form-control form-control-sm" accept="image/*">
                        <small class="text-muted">JPG, PNG, SVG. Recommandé: 200x80px</small>
                    </div>
                    <div class="col-md-8">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Nom de l'agence *</label>
                                <input type="text" name="agence_nom" class="form-control" value="<?= $s('agence_nom') ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Slogan / Description</label>
                                <input type="text" name="agence_slogan" class="form-control" value="<?= $s('agence_slogan') ?>">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-8">
                        <label class="form-label">Adresse</label>
                        <input type="text" name="agence_adresse" class="form-control" value="<?= $s('agence_adresse') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Ville</label>
                        <input type="text" name="agence_ville" class="form-control" value="<?= $s('agence_ville') ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Téléphone</label>
                        <input type="text" name="agence_telephone" class="form-control" value="<?= $s('agence_telephone') ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Téléphone 2 / Mobile</label>
                        <input type="text" name="agence_telephone2" class="form-control" value="<?= $s('agence_telephone2') ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Fax</label>
                        <input type="text" name="agence_fax" class="form-control" value="<?= $s('agence_fax') ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Email</label>
                        <input type="email" name="agence_email" class="form-control" value="<?= $s('agence_email') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Site web</label>
                        <input type="text" name="agence_site_web" class="form-control" value="<?= $s('agence_site_web') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">N° Licence / Autorisation</label>
                        <input type="text" name="agence_licence" class="form-control" value="<?= $s('agence_licence') ?>">
                    </div>
                </div>
            </div>
        </div>
        <button type="submit" class="btn btn-primary btn-lg"><i class="bi bi-check-lg me-2"></i>Enregistrer les paramètres</button>
        </form>
    </div>

    <!-- TAB: Juridique -->
    <div class="tab-pane fade" id="tab-legal">
        <form method="POST">
        <div class="card table-card mb-4">
            <div class="card-header"><i class="bi bi-file-earmark-text me-2"></i>Informations juridiques & fiscales</div>
            <div class="card-body p-4">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label fw-bold">ICE (Identifiant Commun de l'Entreprise)</label>
                        <input type="text" name="agence_ice" class="form-control" value="<?= $s('agence_ice') ?>" placeholder="15 chiffres">
                        <small class="text-muted">Obligatoire sur les factures au Maroc</small>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">IF (Identifiant Fiscal)</label>
                        <input type="text" name="agence_if" class="form-control" value="<?= $s('agence_if') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">RC (Registre de Commerce)</label>
                        <input type="text" name="agence_rc" class="form-control" value="<?= $s('agence_rc') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">CNSS</label>
                        <input type="text" name="agence_cnss" class="form-control" value="<?= $s('agence_cnss') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Patente</label>
                        <input type="text" name="agence_patente" class="form-control" value="<?= $s('agence_patente') ?>">
                    </div>
                </div>
            </div>
        </div>
        <button type="submit" class="btn btn-primary btn-lg"><i class="bi bi-check-lg me-2"></i>Enregistrer les paramètres</button>
        </form>
    </div>

    <!-- TAB: Banque -->
    <div class="tab-pane fade" id="tab-banque">
        <form method="POST">
        <div class="card table-card mb-4">
            <div class="card-header"><i class="bi bi-bank me-2"></i>Coordonnées bancaires</div>
            <div class="card-body p-4">
                <p class="text-muted small mb-3">Ces informations seront affichées sur les factures et reçus pour faciliter les virements.</p>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Nom de la banque</label>
                        <input type="text" name="agence_banque_nom" class="form-control" value="<?= $s('agence_banque_nom') ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Agence</label>
                        <input type="text" name="agence_banque_agence" class="form-control" value="<?= $s('agence_banque_agence') ?>">
                    </div>
                    <div class="col-md-12">
                        <label class="form-label fw-bold">RIB</label>
                        <input type="text" name="agence_banque_rib" class="form-control font-monospace" value="<?= $s('agence_banque_rib') ?>" placeholder="24 chiffres">
                    </div>
                    <div class="col-md-8">
                        <label class="form-label fw-bold">IBAN</label>
                        <input type="text" name="agence_banque_iban" class="form-control font-monospace" value="<?= $s('agence_banque_iban') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Code SWIFT / BIC</label>
                        <input type="text" name="agence_banque_swift" class="form-control font-monospace" value="<?= $s('agence_banque_swift') ?>">
                    </div>
                </div>
            </div>
        </div>
        <button type="submit" class="btn btn-primary btn-lg"><i class="bi bi-check-lg me-2"></i>Enregistrer les paramètres</button>
        </form>
    </div>

    <!-- TAB: Données & Sauvegarde -->
    <div class="tab-pane fade" id="tab-donnees">
        <div class="row g-4">
            <!-- Left Column: Stats & Backup -->
            <div class="col-lg-6">
                <!-- DB Stats -->
                <div class="card table-card h-100">
                    <div class="card-header"><i class="bi bi-bar-chart me-2"></i>Statistiques & Sauvegarde</div>
                    <div class="card-body p-4 text-center d-flex flex-column justify-content-center">
                        <div class="mb-4">
                            <i class="bi bi-database text-primary" style="font-size: 3rem;"></i>
                            <h4 class="mt-2 mb-0"><?= $dbSizeFormatted ?></h4>
                            <p class="text-muted">Taille de la base de données</p>
                        </div>
                        <div class="row g-3 mb-4 text-start">
                            <div class="col-6">
                                <div class="bg-light p-3 rounded">
                                    <h5 class="mb-0 text-success"><?= $tableStats['voyageurs'] ?></h5>
                                    <small class="text-muted">Voyageurs</small>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="bg-light p-3 rounded">
                                    <h5 class="mb-0 text-primary"><?= $tableStats['programmes'] ?></h5>
                                    <small class="text-muted">Programmes</small>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="bg-light p-3 rounded">
                                    <h5 class="mb-0 text-info"><?= $tableStats['inscriptions'] ?></h5>
                                    <small class="text-muted">Inscriptions</small>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="bg-light p-3 rounded">
                                    <h5 class="mb-0 text-warning"><?= $tableStats['paiements'] ?></h5>
                                    <small class="text-muted">Paiements</small>
                                </div>
                            </div>
                        </div>
                        
                        <a href="<?= APP_URL ?>/parametres.php?action=backup" class="btn btn-success btn-lg mt-auto">
                            <i class="bi bi-download me-2"></i>Télécharger la sauvegarde
                        </a>
                        <small class="text-muted mt-2 d-block">Télécharge un fichier .db contenant toutes vos données.</small>
                    </div>
                </div>
            </div>
            
            <!-- Right Column: Restore & Reset -->
            <div class="col-lg-6">
                <!-- Restore -->
                <div class="card table-card mb-4">
                    <div class="card-header"><i class="bi bi-cloud-upload me-2"></i>Restaurer une sauvegarde</div>
                    <div class="card-body p-4">
                        <form method="POST" action="<?= APP_URL ?>/parametres.php?action=restore" enctype="multipart/form-data">
                            <div class="mb-3">
                                <label class="form-label">Sélectionner un fichier (.db)</label>
                                <input type="file" name="backup_file" class="form-control" accept=".db" required>
                            </div>
                            <button type="submit" class="btn btn-warning w-100" onclick="return confirm('Attention : La restauration remplacera toutes les données actuelles. Êtes-vous sûr de vouloir continuer ?')">
                                <i class="bi bi-upload me-2"></i>Restaurer les données
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Reset -->
                <div class="card table-card border-danger">
                    <div class="card-header bg-danger bg-opacity-10 text-danger"><i class="bi bi-exclamation-octagon me-2"></i>Réinitialisation du système</div>
                    <div class="card-body p-4">
                        <p class="small text-danger mb-3">
                            <i class="bi bi-exclamation-triangle-fill me-1"></i>
                            Supprime toutes les données (voyageurs, paiements, etc.) mais conserve les paramètres de l'agence et les comptes utilisateurs.
                        </p>
                        <form method="POST" action="<?= APP_URL ?>/parametres.php?action=reset">
                            <div class="input-group">
                                <input type="text" name="confirm_code" class="form-control border-danger" placeholder="Tapez: REINITIALISER" required autocomplete="off">
                                <button type="submit" class="btn btn-danger">
                                    <i class="bi bi-trash3"></i> Vider
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div><!-- end tab-content -->

<?php
require_once __DIR__ . '/includes/footer.php';
