<?php
include('../includes/config.php');

$logs = [];
$success = false;

// Function to execute SQL file with better error handling
function run_sql_file($con, $filename)
{
    if (!file_exists($filename)) {
        return ["status" => false, "msg" => "File not found: $filename"];
    }

    $sql = file_get_contents($filename);
    if (trim($sql) == "") {
        return ["status" => true, "msg" => "File empty, skipped: $filename"];
    }

    // Attempt execution
    try {
        if (mysqli_multi_query($con, $sql)) {
            do {
                if ($result = mysqli_store_result($con)) {
                    mysqli_free_result($result);
                }
            } while (mysqli_next_result($con));

            return ["status" => true, "msg" => "Executed: $filename"];
        } else {
            return ["status" => false, "msg" => "Error in $filename: " . mysqli_error($con)];
        }
    } catch (Exception $e) {
        return ["status" => false, "msg" => "Exception in $filename: " . $e->getMessage()];
    }
}

// Handle Auto-Run
if (isset($_POST['run_all'])) {

    // 1. Site Settings
    $logs[] = run_sql_file($con, 'create_site_settings.sql');

    // 2. Vendor Tables
    $logs[] = run_sql_file($con, 'create_vendor_tables.sql');

    // 3. Schema Updates (Crucial Step Added)
    $logs[] = run_sql_file($con, 'update_schema.sql');

    // 4. Test Data
    $logs[] = run_sql_file($con, 'test_data.sql');

    // Check overall success
    $success = true;
    foreach ($logs as $log) {
        if (!$log['status'])
            $success = false;
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Complete System Installer</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../__admin__/css/admin-professional.css" rel="stylesheet" />
    <style>
        .log-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
        }

        .log-success {
            color: green;
            border-left: 4px solid green;
            background: #f9fff9;
        }

        .log-error {
            color: red;
            border-left: 4px solid red;
            background: #fff9f9;
        }
    </style>
</head>

<body class="bg-light">
    <div class="container mt-5">
        <div class="card shadow-lg mx-auto" style="max-width: 700px;">
            <div class="card-header bg-dark text-white text-center py-4">
                <h2 class="mb-0"><i class="fas fa-cogs me-2"></i>System Installer</h2>
                <small>Multi-Vendor Marketplace Database Setup</small>
            </div>

            <div class="card-body p-4">
                <!-- Status Logs -->
                <?php if (!empty($logs)): ?>
                    <div class="mb-4 text-start">
                        <h5>Installation Logs:</h5>
                        <div class="border rounded">
                            <?php foreach ($logs as $log): ?>
                                <div class="log-item <?php echo $log['status'] ? 'log-success' : 'log-error'; ?>">
                                    <i
                                        class="fas fa-<?php echo $log['status'] ? 'check-circle' : 'exclamation-circle'; ?> me-2"></i>
                                    <?php echo $log['msg']; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <?php if ($success): ?>
                        <div class="alert alert-success text-center">
                            <h4><i class="fas fa-check-circle me-2"></i>Installation Complete!</h4>
                            <p>All database tables and test data have been configured.</p>
                            <div class="mt-3">
                                <a href="../vendor-login.php" class="btn btn-success me-2">Login as Vendor</a>
                                <a href="../__admin__/" class="btn btn-primary">Login as Admin</a>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-warning text-center">
                            <h4><i class="fas fa-exclamation-triangle me-2"></i>Installation Completed with Issues</h4>
                            <p>Some steps failed. This is usually okay if you are re-running the script.</p>
                            <p>Check the logs above. If 'update_schema.sql' ran, you are good to go.</p>
                        </div>
                    <?php endif; ?>

                    <div class="text-center mt-3">
                        <a href="auto_setup.php" class="btn btn-secondary">Back</a>
                    </div>

                <?php else: ?>
                    <div class="text-center py-3">
                        <div class="mb-4">
                            <span class="badge bg-primary rounded-pill px-3 py-2">4 Steps</span>
                        </div>

                        <div class="list-group text-start mb-4 mx-auto" style="max-width: 400px;">
                            <div class="list-group-item"><i class="fas fa-cog me-2 text-secondary"></i> 1. Site Settings
                            </div>
                            <div class="list-group-item"><i class="fas fa-table me-2 text-secondary"></i> 2. Vendor Tables
                            </div>
                            <div class="list-group-item"><i class="fas fa-wrench me-2 text-primary"></i> 3. Update Existing
                                Tables</div>
                            <div class="list-group-item"><i class="fas fa-user-plus me-2 text-success"></i> 4. Load Test
                                Data</div>
                        </div>

                        <form method="post">
                            <button type="submit" name="run_all" class="btn btn-primary btn-lg w-75 pulse-button">
                                <i class="fas fa-power-off me-2"></i>INSTALL EVERYTHING
                            </button>
                        </form>
                    </div>
                <?php endif; ?>
            </div>
            <div class="card-footer text-center text-muted">
                Safe to run multiple times.
            </div>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>
    <style>
        .pulse-button {
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% {
                transform: scale(1);
                box-shadow: 0 0 0 0 rgba(0, 123, 255, 0.7);
            }

            70% {
                transform: scale(1.02);
                box-shadow: 0 0 0 10px rgba(0, 123, 255, 0);
            }

            100% {
                transform: scale(1);
                box-shadow: 0 0 0 0 rgba(0, 123, 255, 0);
            }
        }
    </style>
</body>

</html>
