<?php
require_once 'config.php';

// SQL to create users table with roles
$sqls = [
    // Users table
    "CREATE TABLE IF NOT EXISTS users (
      id INT AUTO_INCREMENT PRIMARY KEY,
      full_name VARCHAR(100) NOT NULL,
      email VARCHAR(100) UNIQUE NOT NULL,
      password VARCHAR(255) NOT NULL,
      phone VARCHAR(20),
      profile_image VARCHAR(255),
      role ENUM('admin', 'staff', 'broker', 'customer') NOT NULL DEFAULT 'customer',
      broker_id INT,
      status ENUM('active', 'suspended', 'inactive') NOT NULL DEFAULT 'active',
      commission_rate DECIMAL(5, 2),
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      INDEX idx_email (email),
      INDEX idx_role (role),
      INDEX idx_status (status),
      FOREIGN KEY (broker_id) REFERENCES users(id) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",

    // Admin settings table
    "CREATE TABLE IF NOT EXISTS admin_settings (
      id INT AUTO_INCREMENT PRIMARY KEY,
      setting_key VARCHAR(100) UNIQUE NOT NULL,
      setting_value TEXT,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",

    // Roles and permissions table
    "CREATE TABLE IF NOT EXISTS permissions (
      id INT AUTO_INCREMENT PRIMARY KEY,
      role VARCHAR(50) NOT NULL,
      permission VARCHAR(100) NOT NULL,
      UNIQUE KEY unique_role_permission (role, permission)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
];

$success = true;
$messages = [];

foreach ($sqls as $sql) {
    if ($conn->query($sql) === TRUE) {
        $messages[] = "✓ Table created/verified";
    } else {
        $success = false;
        $messages[] = "✗ Error: " . $conn->error;
    }
}

// Insert default admin role permissions if not exists
$defaultPermissions = [
    ['admin', 'view_users'],
    ['admin', 'create_users'],
    ['admin', 'edit_users'],
    ['admin', 'delete_users'],
    ['admin', 'view_properties'],
    ['admin', 'manage_properties'],
    ['admin', 'approve_listings'],
    ['admin', 'view_analytics'],
    ['admin', 'manage_brokers'],
    ['staff', 'view_properties'],
    ['staff', 'update_properties'],
    ['staff', 'respond_inquiries'],
    ['broker', 'view_assigned_properties'],
    ['broker', 'update_property_details'],
    ['broker', 'manage_leads'],
    ['broker', 'schedule_visits'],
    ['customer', 'save_favorites'],
    ['customer', 'view_properties'],
    ['customer', 'schedule_visits'],
];

$conn->query("TRUNCATE TABLE permissions");
foreach ($defaultPermissions as $perm) {
    $conn->query("INSERT INTO permissions (role, permission) VALUES ('{$perm[0]}', '{$perm[1]}')");
}

// Check if admin user exists
$result = $conn->query("SELECT * FROM users WHERE role = 'admin' LIMIT 1");
if ($result->num_rows === 0) {
    // Create default admin user
    $admin_email = 'admin@Zemaraim.com';
    $admin_password = password_hash('admin123', PASSWORD_DEFAULT);
    $conn->query("INSERT INTO users (full_name, email, password, role, status) VALUES ('Admin User', '$admin_email', '$admin_password', 'admin', 'active')");
    $messages[] = "✓ Default admin user created (Email: admin@Zemaraim.com, Password: admin123)";
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Dashboard Setup</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .container { max-width: 800px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h1 { color: #333; text-align: center; }
        .message { padding: 15px; margin: 10px 0; border-radius: 5px; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .info { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; padding: 15px; margin: 20px 0; border-radius: 5px; }
        .button-group { text-align: center; margin-top: 30px; }
        .btn { padding: 12px 30px; background: #667eea; color: white; border: none; border-radius: 5px; cursor: pointer; text-decoration: none; display: inline-block; margin: 0 10px; }
        .btn:hover { background: #764ba2; }
        .credentials { background: #fff3cd; padding: 15px; border-radius: 5px; margin: 20px 0; border: 1px solid #ffc107; }
        .credentials code { background: #f8f9fa; padding: 5px 10px; border-radius: 3px; display: block; margin: 10px 0; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎯 Dashboard System Setup</h1>
        
        <?php if ($success): ?>
            <div class="message success">
                <strong>✓ Setup Completed Successfully!</strong>
            </div>
        <?php else: ?>
            <div class="message error">
                <strong>✗ Some errors occurred during setup</strong>
            </div>
        <?php endif; ?>

        <?php foreach ($messages as $msg): ?>
            <div class="message success"><?php echo $msg; ?></div>
        <?php endforeach; ?>

        <div class="credentials">
            <h3>📝 Admin Login Credentials</h3>
            <p><strong>Email:</strong> <code>admin@Zemaraim.com</code></p>
            <p><strong>Password:</strong> <code>admin123</code></p>
            <p style="color: #856404; font-size: 12px;">⚠️ Please change this password after first login!</p>
        </div>

        <div class="info">
            <h3>ℹ️ System Overview</h3>
            <ul>
                <li><strong>Admin Dashboard:</strong> Complete system management and analytics</li>
                <li><strong>Staff Dashboard:</strong> Operational tasks and inquiries</li>
                <li><strong>Broker Dashboard:</strong> Sales and lead management for assigned properties</li>
                <li><strong>Customer Dashboard:</strong> Personalized property browsing and favorites</li>
            </ul>
        </div>

        <div class="button-group">
            <a href="admin-login.php" class="btn">Go to Admin Login</a>
            <a href="index.php" class="btn" style="background: #999;">Back to Home</a>
        </div>
    </div>
</body>
</html>

<?php $conn->close(); ?>
