<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/auth.php';

// Only allow admins to access this script
if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    header('HTTP/1.0 403 Forbidden');
    die('Access Denied: You do not have permission to access this page.');
}

// Confirmation step
$confirmed = isset($_POST['confirm']) && $_POST['confirm'] === 'yes';
$success = false;
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $confirmed) {
    try {
        $pdo->beginTransaction();
        
        // Disable foreign key checks temporarily
        $pdo->exec('SET FOREIGN_KEY_CHECKS = 0');
        
        // Get all tables
        $tables = $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN);
        
        // Exclude tables you want to keep (if any)
        $tablesToKeep = ['migrations', 'config'];
        $tables = array_diff($tables, $tablesToKeep);
        
        foreach ($tables as $table) {
            // Skip views
            $stmt = $pdo->query("SHOW TABLE STATUS LIKE '$table'");
            $tableInfo = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($tableInfo['Comment'] !== 'VIEW') {
                $pdo->exec("TRUNCATE TABLE `$table`");
                $pdo->exec("ALTER TABLE `$table` AUTO_INCREMENT = 1");
            }
        }
        
        // Re-enable foreign key checks
        $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
        
        $pdo->commit();
        $success = true;
        $message = 'Database has been cleared successfully!';
        
    } catch (PDOException $e) {
        $pdo->rollBack();
        $message = 'Error: ' . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clear Database</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center">
    <div class="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
        <h1 class="text-2xl font-bold text-red-600 mb-6">⚠️ Clear Database</h1>
        
        <?php if ($message): ?>
            <div class="mb-6 p-4 rounded-md <?php echo $success ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'; ?>">
                <?php echo $message; ?>
            </div>
            
            <?php if ($success): ?>
                <div class="mt-6">
                    <a href="/admin/" class="text-blue-600 hover:underline">← Back to Admin Panel</a>
                </div>
            <?php endif; ?>
            
        <?php else: ?>
            <div class="mb-6">
                <p class="text-gray-700 mb-4">This action will permanently delete all data from the database. This cannot be undone.</p>
                <p class="text-red-600 font-semibold">Please make sure you have a backup before proceeding.</p>
            </div>
            
            <form method="post" onsubmit="return confirm('Are you absolutely sure you want to clear the database? This action cannot be undone.');">
                <input type="hidden" name="confirm" value="yes">
                <div class="flex justify-between items-center">
                    <a href="/admin/" class="text-blue-600 hover:underline">Cancel</a>
                    <button type="submit" class="bg-red-600 hover:bg-red-700 text-white font-medium py-2 px-4 rounded-md transition duration-200">
                        I understand, clear all data
                    </button>
                </div>
            </form>
        <?php endif; ?>
    </div>
</body>
</html>
