<?php
/**
 * Enterprise HRM ERP System - Create Branch Permissions Table
 * Run this once to create the branch permissions table
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

// Check if user is Super Admin
startSession();
$roleCode = $_SESSION['role_code'] ?? '';
if (empty($roleCode) && isset($_SESSION['user_id'])) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT r.role_code 
            FROM users u
            INNER JOIN roles r ON u.role_id = r.role_id
            WHERE u.user_id = ?
        ");
        $stmt->execute([$_SESSION['user_id']]);
        $userRole = $stmt->fetch();
        if ($userRole && !empty($userRole['role_code'])) {
            $roleCode = $userRole['role_code'];
            $_SESSION['role_code'] = $roleCode;
        }
    } catch (Exception $e) {
        error_log("Error loading role_code: " . $e->getMessage());
    }
}

if (strtolower($roleCode) !== 'super_admin') {
    die('Only Super Admin can run this script.');
}

$success = false;
$error = null;

try {
    $db = getDB();
    
    // Check if table already exists
    $stmt = $db->query("SHOW TABLES LIKE 'site_role_permissions'");
    if ($stmt->rowCount() > 0) {
        $success = true;
        $message = 'Table already exists.';
    } else {
        // Create table
        $db->exec("
            CREATE TABLE IF NOT EXISTS `site_role_permissions` (
              `site_role_permission_id` int(11) NOT NULL AUTO_INCREMENT,
              `site_id` int(11) NOT NULL,
              `role_id` int(11) NOT NULL,
              `permission_id` int(11) NOT NULL,
              `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
              `created_by` int(11),
              PRIMARY KEY (`site_role_permission_id`),
              UNIQUE KEY `unique_site_role_permission` (`site_id`,`role_id`,`permission_id`),
              KEY `fk_site_role_permission_site` (`site_id`),
              KEY `fk_site_role_permission_role` (`role_id`),
              KEY `fk_site_role_permission_permission` (`permission_id`),
              KEY `fk_site_role_permission_created_by` (`created_by`),
              CONSTRAINT `fk_site_role_permission_site` FOREIGN KEY (`site_id`) REFERENCES `sites` (`site_id`) ON DELETE CASCADE,
              CONSTRAINT `fk_site_role_permission_role` FOREIGN KEY (`role_id`) REFERENCES `roles` (`role_id`) ON DELETE CASCADE,
              CONSTRAINT `fk_site_role_permission_permission` FOREIGN KEY (`permission_id`) REFERENCES `permissions` (`permission_id`) ON DELETE CASCADE,
              CONSTRAINT `fk_site_role_permission_created_by` FOREIGN KEY (`created_by`) REFERENCES `users` (`user_id`) ON DELETE SET NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        
        $success = true;
        $message = 'Branch permissions table created successfully!';
    }
} catch (Exception $e) {
    $error = $e->getMessage();
    error_log("Error creating branch permissions table: " . $error);
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Branch Permissions Table</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .card {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .success {
            background: #d1fae5;
            color: #065f46;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
        }
        .error {
            background: #fee2e2;
            color: #991b1b;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
        }
        .btn {
            display: inline-block;
            padding: 10px 20px;
            background: #1e293b;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            margin-top: 20px;
        }
        .btn:hover {
            background: #1d4ed8;
        }
    </style>
</head>
<body>
    <div class="card">
        <h1>Create Branch Permissions Table</h1>
        
        <?php if ($success): ?>
        <div class="success">
            <strong>Success!</strong> <?php echo htmlspecialchars($message); ?>
        </div>
        <p>You can now use the Branch Permissions Management feature.</p>
        <a href="<?php echo BASE_URL; ?>/admin/branch_permissions.php" class="btn">Go to Branch Permissions</a>
        <a href="<?php echo BASE_URL; ?>/modules/settings/index.php" class="btn" style="background: #6b7280;">Back to Settings</a>
        <?php else: ?>
        <div class="error">
            <strong>Error!</strong> <?php echo htmlspecialchars($error ?? 'Unknown error occurred.'); ?>
        </div>
        <a href="<?php echo BASE_URL; ?>/modules/settings/index.php" class="btn">Back to Settings</a>
        <?php endif; ?>
    </div>
</body>
</html>

