<?php
session_start();
require_once '../config.php';

requireAdmin();

$page_title = 'System Setup & Installation';

$setup_status = [];
$messages = [];

// Check existing tables
$tables_to_check = [
    'email_logs' => 'Email Logging',
    'admin_users' => 'Multi-Admin Support',
    'system_settings' => 'System Settings',
    'appointment_reminders' => 'Appointment Reminders',
    'user_2fa' => '2FA Authentication',
    'audit_logs' => 'Audit Logging',
    'doctor_availability' => 'Doctor Availability Slots',
    'consultation_notes' => 'Consultation Notes',
    'payment_plans' => 'Payment Plans'
];

$db_name = DB_NAME;
foreach ($tables_to_check as $table => $label) {
    $result = $conn->query("SELECT 1 FROM information_schema.TABLES WHERE table_schema = '$db_name' AND table_name = '$table'");
    $setup_status[$label] = [
        'table' => $table,
        'exists' => $result && $result->num_rows > 0,
        'status' => 'ready'
    ];
}

// Handle installation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'install_all') {
        // Execute migration SQL
        $migration_file = __DIR__ . '/../migration_complete_features.sql';
        if (file_exists($migration_file)) {
            $sql = file_get_contents($migration_file);
            // Split by semicolon and execute each statement
            $statements = array_filter(array_map('trim', explode(';', $sql)));
            $success_count = 0;
            $error_count = 0;
            
            foreach ($statements as $statement) {
                if (!empty($statement)) {
                    if ($conn->query($statement)) {
                        $success_count++;
                    } else {
                        $error_count++;
                        $messages[] = ['type' => 'warning', 'text' => "Error: " . $conn->error];
                    }
                }
            }
            
            if ($error_count === 0) {
                $messages[] = ['type' => 'success', 'text' => "Installation successful! $success_count features installed."];
            } else {
                $messages[] = ['type' => 'warning', 'text' => "Installation complete with some warnings. Success: $success_count, Errors: $error_count"];
            }
            
            // Refresh status
            foreach ($tables_to_check as $table => $label) {
                $result = $conn->query("SELECT 1 FROM information_schema.TABLES WHERE table_schema = '$db_name' AND table_name = '$table'");
                $setup_status[$label]['exists'] = $result && $result->num_rows > 0;
            }
        } else {
            $messages[] = ['type' => 'danger', 'text' => 'Migration file not found!'];
        }
    } elseif ($_POST['action'] === 'create_default_admin') {
        $admin_name = 'Super Admin';
        $admin_email = 'admin@healthlink.com';
        $admin_password = password_hash('admin123', PASSWORD_BCRYPT);
        $role = 'super_admin';
        
        $stmt = $conn->prepare("INSERT INTO admin_users (full_name, email, password_hash, role) VALUES (?, ?, ?, ?)");
        if ($stmt) {
            $stmt->bind_param('ssss', $admin_name, $admin_email, $admin_password, $role);
            if ($stmt->execute()) {
                $messages[] = ['type' => 'success', 'text' => 'Default admin created! Email: admin@healthlink.com | Password: admin123'];
            } else {
                $messages[] = ['type' => 'danger', 'text' => 'Error creating admin: ' . $stmt->error];
            }
        }
    }
}

include 'header.php';
?>

                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="fas fa-cogs text-primary"></i> System Setup & Installation
                    </h1>
                </div>

                <?php foreach ($messages as $msg): ?>
                    <div class="alert alert-<?= $msg['type'] ?> alert-dismissible fade show" role="alert">
                        <?= htmlspecialchars($msg['text']) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endforeach; ?>

                <!-- Installation Status -->
                <div class="card mb-4">
                    <div class="card-header bg-light">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="card-title mb-0"><i class="fas fa-clipboard-check"></i> Feature Installation Status</h5>
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="action" value="install_all">
                                <button type="submit" class="btn btn-success btn-sm" onclick="return confirm('This will create/update all necessary database tables. Continue?')">
                                    <i class="fas fa-download"></i> Install All Features
                                </button>
                            </form>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <?php foreach ($setup_status as $label => $info): ?>
                                <div class="col-md-6 mb-3">
                                    <div class="d-flex align-items-center p-3 border rounded">
                                        <div class="me-3">
                                            <?php if ($info['exists']): ?>
                                                <i class="fas fa-check-circle text-success fa-2x"></i>
                                            <?php else: ?>
                                                <i class="fas fa-times-circle text-danger fa-2x"></i>
                                            <?php endif; ?>
                                        </div>
                                        <div>
                                            <h6 class="mb-0"><?= $label ?></h6>
                                            <small class="text-muted"><?= $info['exists'] ? 'Installed' : 'Not installed' ?></small>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <!-- Quick Setup Options -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-light">
                                <h5 class="card-title mb-0"><i class="fas fa-user-shield"></i> Admin Users</h5>
                            </div>
                            <div class="card-body">
                                <p>Create additional admin accounts for team members.</p>
                                <a href="admin-users.php" class="btn btn-primary btn-sm">
                                    <i class="fas fa-users-cog"></i> Manage Admin Users
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-light">
                                <h5 class="card-title mb-0"><i class="fas fa-sliders-h"></i> Settings</h5>
                            </div>
                            <div class="card-body">
                                <p>Configure system settings and preferences.</p>
                                <a href="settings.php" class="btn btn-primary btn-sm">
                                    <i class="fas fa-cog"></i> Go to Settings
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- System Information -->
                <div class="card mt-4">
                    <div class="card-header bg-light">
                        <h5 class="card-title mb-0"><i class="fas fa-info-circle"></i> System Information</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <table class="table table-sm">
                                    <tr>
                                        <td><strong>PHP Version:</strong></td>
                                        <td><?= phpversion() ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>MySQL Version:</strong></td>
                                        <td><?= $conn->get_server_info() ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Database:</strong></td>
                                        <td><?= DB_NAME ?></td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table class="table table-sm">
                                    <tr>
                                        <td><strong>Upload Path:</strong></td>
                                        <td><?= UPLOAD_PATH ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Site URL:</strong></td>
                                        <td><?= SITE_URL ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Server Time:</strong></td>
                                        <td><?= date('Y-m-d H:i:s') ?></td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

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