<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php'); // Original school DB
require_once('source/dbconfig4.php'); // New central settings DB
require_once('source/function.php');
require_once('source/restrict_admin.php');

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_branch'])) {
        $branchCode = $_POST['branch_code'];
        $updateData = [
            'branch_name' => $_POST['branch_name'],
            'branch_address' => $_POST['branch_address'],
            'branch_short_name' => $_POST['branch_short_name'],
            'school_motto' => $_POST['school_motto'],
            'contact_phone' => $_POST['contact_phone'],
            'contact_email' => $_POST['contact_email'],
            'result_portal_url' => $_POST['result_portal_url'],
            'footer_text' => $_POST['footer_text'],
            'footer_copyright' => $_POST['footer_copyright']
        ];
        
        // Handle logo upload
        if (isset($_FILES['school_logo']) && $_FILES['school_logo']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = '../uploads/logos/';
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            $fileExt = pathinfo($_FILES['school_logo']['name'], PATHINFO_EXTENSION);
            $fileName = $branchCode . '_logo.' . $fileExt;
            $uploadPath = $uploadDir . $fileName;
            
            if (move_uploaded_file($_FILES['school_logo']['tmp_name'], $uploadPath)) {
                $updateData['school_logo_path'] = 'uploads/logos/' . $fileName;
            }
        }
        
        // Update in central database
        $setParts = [];
        $params = [];
        foreach ($updateData as $key => $value) {
            $setParts[] = "$key = ?";
            $params[] = $value;
        }
        $params[] = $branchCode;
        
        $sql = "UPDATE school_branches SET " . implode(', ', $setParts) . " WHERE branch_code = ?";
        $stmt = $CENTRAL_DB->prepare($sql);
        
        if ($stmt->execute($params)) {
            $_SESSION['msg'] = "Settings updated successfully!";
        } else {
            $_SESSION['msg'] = "Error updating settings.";
        }
        
        header("Location: portal_settings.php?branch=" . $branchCode);
        exit();
    }
}

// Get branch code from URL or use current
$branchCode = isset($_GET['branch']) ? $_GET['branch'] : $currentBranchCode;
$branchSettings = $branchCode ? getSchoolSettings($branchCode) : null;
$allBranches = getAllBranches();

// Get system settings
$systemSettings = [];
$stmt = $CENTRAL_DB->query("SELECT * FROM system_settings");
while ($row = $stmt->fetch()) {
    $systemSettings[$row['setting_key']] = $row['setting_value'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Portal Settings - Multi-Branch Manager</title>
    <link rel="icon" type="image/png" href="../<?php echo defined('SCHOOL_LOGO') ? SCHOOL_LOGO : 'coll_logo.png'; ?>">
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary-blue: #1a4b8c;
            --secondary-gold: #FFD700;
            --dark-blue: #0f2b4f;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f5f7fa;
            padding-top: 56px;
        }
        
        .settings-container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 1rem;
        }
        
        .settings-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            overflow: hidden;
            border: 1px solid rgba(255,215,0,0.3);
            margin-bottom: 2rem;
        }
        
        .settings-header {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
            padding: 1.5rem;
            border-bottom: 3px solid var(--secondary-gold);
        }
        
        .settings-header h4 {
            margin: 0;
            font-weight: 600;
        }
        
        .settings-body {
            padding: 2rem;
        }
        
        .branch-selector {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 2rem;
            border-left: 4px solid var(--secondary-gold);
        }
        
        .form-label {
            font-weight: 500;
            color: var(--dark-blue);
        }
        
        .form-control, .form-select {
            border-radius: 8px;
            border: 1px solid #ddd;
            padding: 0.6rem 1rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--secondary-gold);
            box-shadow: 0 0 0 0.2rem rgba(255,215,0,0.25);
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            border: none;
            padding: 0.6rem 2rem;
            font-weight: 500;
            border: 1px solid var(--secondary-gold);
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, var(--secondary-gold), #e6b800);
            color: var(--dark-blue);
        }
        
        .current-logo {
            max-width: 100px;
            max-height: 100px;
            border-radius: 8px;
            border: 2px solid var(--secondary-gold);
            padding: 0.25rem;
            background: white;
        }
        
        .info-box {
            background: #e8f0fe;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            border-left: 4px solid var(--primary-blue);
        }
        
        .info-box i {
            color: var(--secondary-gold);
            margin-right: 0.5rem;
        }
        
        .nav-tabs .nav-link {
            color: var(--dark-blue);
            font-weight: 500;
        }
        
        .nav-tabs .nav-link.active {
            color: var(--primary-blue);
            border-bottom: 3px solid var(--secondary-gold);
            font-weight: 600;
        }
        
        .branch-badge {
            background: var(--secondary-gold);
            color: var(--dark-blue);
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            display: inline-block;
        }
    </style>
</head>
<body>
    <!-- Top Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark fixed-top" style="background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue)); border-bottom: 2px solid var(--secondary-gold);">
        <div class="container-fluid">
            <a class="navbar-brand" href="main.php">
                <img src="../<?php echo defined('SCHOOL_LOGO') ? SCHOOL_LOGO : 'coll_logo.png'; ?>" alt="Logo" height="35" class="me-2" style="border-radius: 4px;">
                Portal Settings Manager
            </a>
            <div class="ms-auto">
                <a href="main.php" class="btn btn-outline-light btn-sm me-2">
                    <i class="fas fa-arrow-left"></i> Back to Dashboard
                </a>
                <?php if (defined('SCHOOL_BRANCH_NAME')): ?>
                <span class="text-white me-3">
                    <i class="fas fa-map-marker-alt" style="color: var(--secondary-gold);"></i>
                    <?php echo SCHOOL_BRANCH_NAME; ?>
                </span>
                <?php endif; ?>
            </div>
        </div>
    </nav>

    <div class="settings-container">
        <!-- Branch Selector -->
        <div class="branch-selector">
            <form method="get" class="row align-items-end">
                <div class="col-md-10">
                    <label class="form-label"><i class="fas fa-school me-2" style="color: var(--secondary-gold);"></i>Select Branch to Configure:</label>
                    <select name="branch" class="form-select" onchange="this.form.submit()">
                        <option value="">-- Select Branch --</option>
                        <?php if ($allBranches): ?>
                            <?php foreach ($allBranches as $branch): ?>
                            <option value="<?php echo htmlspecialchars($branch['branch_code']); ?>" 
                                    <?php echo ($branchCode == $branch['branch_code']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($branch['branch_name']); ?> - 
                                <?php echo htmlspecialchars(substr($branch['branch_address'], 0, 30)); ?>... 
                                (<?php echo htmlspecialchars($branch['branch_code']); ?>)
                            </option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-sync-alt"></i> Load
                    </button>
                </div>
            </form>
        </div>

        <?php if ($branchSettings): ?>
        <!-- Branch Info Badge -->
        <div class="text-center mb-3">
            <span class="branch-badge">
                <i class="fas fa-database me-1"></i>
                Database: <?php echo htmlspecialchars($branchSettings['database_name']); ?>
            </span>
            <span class="branch-badge ms-2">
                <i class="fas fa-code me-1"></i>
                Code: <?php echo htmlspecialchars($branchSettings['branch_code']); ?>
            </span>
        </div>

        <!-- Settings Tabs -->
        <ul class="nav nav-tabs mb-4" id="settingsTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="branch-tab" data-bs-toggle="tab" data-bs-target="#branch" type="button" role="tab">
                    <i class="fas fa-school me-2"></i>Branch Settings
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="appearance-tab" data-bs-toggle="tab" data-bs-target="#appearance" type="button" role="tab">
                    <i class="fas fa-paint-brush me-2"></i>Appearance
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact" type="button" role="tab">
                    <i class="fas fa-address-card me-2"></i>Contact Info
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="footer-tab" data-bs-toggle="tab" data-bs-target="#footer" type="button" role="tab">
                    <i class="fas fa-file-alt me-2"></i>Footer Settings
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="system-tab" data-bs-toggle="tab" data-bs-target="#system" type="button" role="tab">
                    <i class="fas fa-cogs me-2"></i>System Settings
                </button>
            </li>
        </ul>

        <!-- Tab Content -->
        <div class="tab-content" id="settingsTabsContent">
            <!-- Branch Settings Tab -->
            <div class="tab-pane fade show active" id="branch" role="tabpanel">
                <div class="settings-card">
                    <div class="settings-header">
                        <h4><i class="fas fa-school me-2" style="color: var(--secondary-gold);"></i>Branch Information</h4>
                    </div>
                    <div class="settings-body">
                        <form method="post" enctype="multipart/form-data">
                            <input type="hidden" name="branch_code" value="<?php echo htmlspecialchars($branchSettings['branch_code']); ?>">
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Branch Name</label>
                                    <input type="text" class="form-control" name="branch_name" 
                                           value="<?php echo htmlspecialchars($branchSettings['branch_name']); ?>" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Branch Code</label>
                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($branchSettings['branch_code']); ?>" readonly disabled>
                                    <small class="text-muted">Used for database identification</small>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Branch Address</label>
                                <textarea class="form-control" name="branch_address" rows="2" required><?php echo htmlspecialchars($branchSettings['branch_address']); ?></textarea>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Short Name/Acronym</label>
                                    <input type="text" class="form-control" name="branch_short_name" 
                                           value="<?php echo htmlspecialchars($branchSettings['branch_short_name']); ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">School Motto</label>
                                    <input type="text" class="form-control" name="school_motto" 
                                           value="<?php echo htmlspecialchars($branchSettings['school_motto']); ?>">
                                </div>
                            </div>
                            
                            <div class="info-box">
                                <i class="fas fa-database"></i>
                                <strong>Database:</strong> <?php echo htmlspecialchars($branchSettings['database_name']); ?>
                                <span class="badge bg-success ms-2">Active</span>
                            </div>
                            
                            <button type="submit" name="update_branch" class="btn btn-primary">
                                <i class="fas fa-save me-2"></i>Save Branch Settings
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Appearance Tab -->
            <div class="tab-pane fade" id="appearance" role="tabpanel">
                <div class="settings-card">
                    <div class="settings-header">
                        <h4><i class="fas fa-paint-brush me-2" style="color: var(--secondary-gold);"></i>Appearance Settings</h4>
                    </div>
                    <div class="settings-body">
                        <form method="post" enctype="multipart/form-data">
                            <input type="hidden" name="branch_code" value="<?php echo htmlspecialchars($branchSettings['branch_code']); ?>">
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Current Logo</label><br>
                                    <img src="../<?php echo htmlspecialchars($branchSettings['school_logo_path']); ?>" 
                                         alt="Current Logo" class="current-logo mb-2" onerror="this.src='../coll_logo.png';">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Upload New Logo</label>
                                    <input type="file" class="form-control" name="school_logo" accept="image/*">
                                    <small class="text-muted">Recommended size: 200x200px</small>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Result Portal URL</label>
                                <input type="url" class="form-control" name="result_portal_url" 
                                       value="<?php echo htmlspecialchars($branchSettings['result_portal_url']); ?>">
                                <small class="text-muted">URL where parents check results</small>
                            </div>
                            
                            <button type="submit" name="update_branch" class="btn btn-primary">
                                <i class="fas fa-save me-2"></i>Save Appearance Settings
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Contact Info Tab -->
            <div class="tab-pane fade" id="contact" role="tabpanel">
                <div class="settings-card">
                    <div class="settings-header">
                        <h4><i class="fas fa-address-card me-2" style="color: var(--secondary-gold);"></i>Contact Information</h4>
                    </div>
                    <div class="settings-body">
                        <form method="post">
                            <input type="hidden" name="branch_code" value="<?php echo htmlspecialchars($branchSettings['branch_code']); ?>">
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Contact Phone</label>
                                    <input type="text" class="form-control" name="contact_phone" 
                                           value="<?php echo htmlspecialchars($branchSettings['contact_phone']); ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Contact Email</label>
                                    <input type="email" class="form-control" name="contact_email" 
                                           value="<?php echo htmlspecialchars($branchSettings['contact_email']); ?>">
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Website URL</label>
                                <input type="url" class="form-control" name="website_url" 
                                       value="<?php echo htmlspecialchars($branchSettings['website_url']); ?>">
                            </div>
                            
                            <button type="submit" name="update_branch" class="btn btn-primary">
                                <i class="fas fa-save me-2"></i>Save Contact Info
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Footer Settings Tab -->
            <div class="tab-pane fade" id="footer" role="tabpanel">
                <div class="settings-card">
                    <div class="settings-header">
                        <h4><i class="fas fa-file-alt me-2" style="color: var(--secondary-gold);"></i>Footer Settings</h4>
                    </div>
                    <div class="settings-body">
                        <form method="post">
                            <input type="hidden" name="branch_code" value="<?php echo htmlspecialchars($branchSettings['branch_code']); ?>">
                            
                            <div class="mb-3">
                                <label class="form-label">Footer Text</label>
                                <textarea class="form-control" name="footer_text" rows="2"><?php echo htmlspecialchars($branchSettings['footer_text']); ?></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Copyright Text</label>
                                <input type="text" class="form-control" name="footer_copyright" 
                                       value="<?php echo htmlspecialchars($branchSettings['footer_copyright']); ?>">
                            </div>
                            
                            <button type="submit" name="update_branch" class="btn btn-primary">
                                <i class="fas fa-save me-2"></i>Save Footer Settings
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- System Settings Tab (Global) -->
            <div class="tab-pane fade" id="system" role="tabpanel">
                <div class="settings-card">
                    <div class="settings-header">
                        <h4><i class="fas fa-cogs me-2" style="color: var(--secondary-gold);"></i>System-wide Settings</h4>
                    </div>
                    <div class="settings-body">
                        <div class="info-box">
                            <i class="fas fa-globe"></i>
                            These settings apply to all branches
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">System Name</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($systemSettings['system_name'] ?? 'School Management System'); ?>" readonly>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Developer</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($systemSettings['developer_name'] ?? 'DataSwift Coders'); ?>" readonly>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Support Phone</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($systemSettings['support_phone'] ?? '+234 803 292 9756'); ?>" readonly>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Support Email</label>
                                <input type="email" class="form-control" value="<?php echo htmlspecialchars($systemSettings['support_email'] ?? 'support@dataswift.com.ng'); ?>" readonly>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Developer Website</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($systemSettings['developer_website'] ?? 'https://dataswift.com.ng'); ?>" readonly>
                        </div>
                        
                        <a href="#" class="btn btn-outline-secondary" onclick="alert('Contact developer to modify system settings'); return false;">
                            <i class="fas fa-lock me-2"></i>System Settings Locked
                        </a>
                    </div>
                </div>
            </div>
        </div>
        <?php else: ?>
        <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle me-2"></i>
            Please select a branch to configure settings.
        </div>
        <?php endif; ?>
    </div>

    <!-- Bootstrap 5 JS Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Show message if exists
        <?php if (isset($_SESSION['msg'])): ?>
        alert("<?php echo addslashes($_SESSION['msg']); ?>");
        <?php unset($_SESSION['msg']); ?>
        <?php endif; ?>
        
        // Handle tab persistence
        document.addEventListener('DOMContentLoaded', function() {
            const hash = window.location.hash;
            if (hash) {
                const tab = document.querySelector(`[data-bs-target="${hash}"]`);
                if (tab) {
                    new bootstrap.Tab(tab).show();
                }
            }
            
            // Update URL hash when tab changes
            const tabs = document.querySelectorAll('[data-bs-toggle="tab"]');
            tabs.forEach(tab => {
                tab.addEventListener('shown.bs.tab', function (e) {
                    window.location.hash = e.target.getAttribute('data-bs-target');
                });
            });
        });
    </script>
</body>
</html>