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

// Check if user is Super Admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== 0) {
    header("location: login.php");
    exit;
}

$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$phone_number = $photo = $email = "";
$success_message = $error_message = "";

// Fetch user details
if (isset($conn) && $conn instanceof mysqli) {
    $sql = "SELECT username, email, phone_number, photo FROM users WHERE id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("i", $user_id);
        if ($stmt->execute()) {
            $stmt->bind_result($username_db, $email_db, $phone_number_db, $photo_db);
            $stmt->fetch();
            $username = htmlspecialchars($username_db ?? '');
            $email = htmlspecialchars($email_db ?? '');
            $phone_number = htmlspecialchars($phone_number_db ?? '');
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="80" height="80"%3E%3Crect width="80" height="80" fill="%234f46e5"/%3E%3Ctext x="50%25" y="50%25" dominant-baseline="middle" text-anchor="middle" font-family="Arial, sans-serif" font-size="32" font-weight="bold" fill="white"%3ESA%3C/text%3E%3C/svg%3E';
        }
        $stmt->close();
    }
}

// Handle profile photo upload
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['upload_photo'])) {
    if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] == 0) {
        $allowed_types = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
        $max_size = 5 * 1024 * 1024; // 5MB
        
        $file_type = $_FILES['profile_photo']['type'];
        $file_size = $_FILES['profile_photo']['size'];
        
        if (!in_array($file_type, $allowed_types)) {
            $error_message = "Invalid file type. Only JPG, PNG, and GIF are allowed.";
        } elseif ($file_size > $max_size) {
            $error_message = "File size too large. Maximum size is 5MB.";
        } else {
            $upload_dir = 'uploads/profiles/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            $file_extension = pathinfo($_FILES['profile_photo']['name'], PATHINFO_EXTENSION);
            $new_filename = 'profile_' . $user_id . '_' . time() . '.' . $file_extension;
            $upload_path = $upload_dir . $new_filename;
            
            if (move_uploaded_file($_FILES['profile_photo']['tmp_name'], $upload_path)) {
                // Delete old photo if it exists and is not the default SVG
                if (!empty($photo_db) && strpos($photo_db, 'data:image/svg') === false && file_exists($photo_db)) {
                    unlink($photo_db);
                }
                
                // Update database
                if (isset($conn) && $conn instanceof mysqli) {
                    $sql = "UPDATE users SET photo = ? WHERE id = ?";
                    if ($stmt = $conn->prepare($sql)) {
                        $stmt->bind_param("si", $upload_path, $user_id);
                        if ($stmt->execute()) {
                            $success_message = "Profile photo updated successfully!";
                            $photo = htmlspecialchars($upload_path);
                        } else {
                            $error_message = "Error updating photo in database.";
                        }
                        $stmt->close();
                    }
                }
            } else {
                $error_message = "Error uploading file.";
            }
        }
    } else {
        $error_message = "Please select a photo to upload.";
    }
}

// Handle profile update
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_profile'])) {
    $new_username = trim($_POST['username']);
    $new_email = trim($_POST['email']);
    $new_phone = trim($_POST['phone_number']);
    
    if (isset($conn) && $conn instanceof mysqli) {
        $sql = "UPDATE users SET username = ?, email = ?, phone_number = ? WHERE id = ?";
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("sssi", $new_username, $new_email, $new_phone, $user_id);
            if ($stmt->execute()) {
                $_SESSION['username'] = $new_username;
                $success_message = "Profile updated successfully!";
                $username = htmlspecialchars($new_username);
                $email = htmlspecialchars($new_email);
                $phone_number = htmlspecialchars($new_phone);
            } else {
                $error_message = "Error updating profile.";
            }
            $stmt->close();
        }
    }
}

// Handle password change
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['change_password'])) {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    if ($new_password !== $confirm_password) {
        $error_message = "New passwords do not match.";
    } else {
        if (isset($conn) && $conn instanceof mysqli) {
            // Verify current password
            $sql = "SELECT password FROM users WHERE id = ?";
            if ($stmt = $conn->prepare($sql)) {
                $stmt->bind_param("i", $user_id);
                $stmt->execute();
                $stmt->bind_result($hashed_password);
                $stmt->fetch();
                $stmt->close();
                
                if (password_verify($current_password, $hashed_password)) {
                    // Update password
                    $new_hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                    $sql = "UPDATE users SET password = ? WHERE id = ?";
                    if ($stmt = $conn->prepare($sql)) {
                        $stmt->bind_param("si", $new_hashed_password, $user_id);
                        if ($stmt->execute()) {
                            $success_message = "Password changed successfully!";
                        } else {
                            $error_message = "Error changing password.";
                        }
                        $stmt->close();
                    }
                } else {
                    $error_message = "Current password is incorrect.";
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Settings - Super Admin</title>
    <link rel="stylesheet" href="super_admin_layout.css">
    <link rel="icon" href="images/logo.png" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Fixed Layout Styles */
        body {
            margin: 0;
            padding: 0;
            height: 100vh;
            overflow: hidden;
        }

        .dashboard-container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            overflow-y: auto;
            z-index: 1000;
        }

        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
            margin-left: 250px;
        }

        .header {
            position: sticky;
            top: 0;
            z-index: 999;
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .dashboard-content {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 20px;
        }

        @media (max-width: 768px) {
            .main-content {
                margin-left: 0;
            }
        }

        .settings-container {
            max-width: 1000px;
            margin: 0 auto;
        }

        .settings-card {
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.08);
            margin-bottom: 30px;
        }

        .settings-card h3 {
            color: #333;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #555;
        }

        .form-group input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .form-group input:focus {
            outline: none;
            border-color: #4f46e5;
        }

        .btn-primary {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
            color: white;
            padding: 14px 30px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(79, 70, 229, 0.3);
        }

        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .alert-success {
            background-color: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .alert-error {
            background-color: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        .profile-photo-section {
            text-align: center;
            margin-bottom: 30px;
            position: relative;
        }

        .profile-photo-wrapper {
            position: relative;
            display: inline-block;
            margin-bottom: 15px;
        }

        .profile-photo-section img {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            object-fit: cover;
            border: 5px solid #4f46e5;
            box-shadow: 0 4px 15px rgba(79, 70, 229, 0.2);
            transition: all 0.3s;
        }

        .profile-photo-section img:hover {
            transform: scale(1.05);
            box-shadow: 0 6px 25px rgba(79, 70, 229, 0.3);
        }

        .photo-upload-overlay {
            position: absolute;
            bottom: 0;
            right: 0;
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
            width: 45px;
            height: 45px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            border: 3px solid white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            transition: all 0.3s;
        }

        .photo-upload-overlay:hover {
            transform: scale(1.1);
            box-shadow: 0 4px 15px rgba(79, 70, 229, 0.4);
        }

        .photo-upload-overlay i {
            color: white;
            font-size: 18px;
        }

        .photo-upload-form {
            background: #f9fafb;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
            border: 2px dashed #d1d5db;
        }

        .photo-upload-form.active {
            border-color: #4f46e5;
            background: #f0f9ff;
        }

        .file-input-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
        }

        .file-input-wrapper input[type=file] {
            position: absolute;
            left: -9999px;
        }

        .file-input-label {
            display: inline-block;
            padding: 12px 24px;
            background: white;
            border: 2px solid #4f46e5;
            color: #4f46e5;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s;
        }

        .file-input-label:hover {
            background: #4f46e5;
            color: white;
        }

        .file-preview {
            margin-top: 15px;
            padding: 10px;
            background: white;
            border-radius: 6px;
            display: none;
        }

        .file-preview.active {
            display: block;
        }

        .btn-upload {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            margin-top: 15px;
            transition: all 0.3s;
        }

        .btn-upload:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(16, 185, 129, 0.3);
        }

        .settings-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 30px;
            border-bottom: 2px solid #f0f0f0;
        }

        .settings-tab {
            padding: 12px 24px;
            background: none;
            border: none;
            border-bottom: 3px solid transparent;
            cursor: pointer;
            font-weight: 600;
            color: #666;
            transition: all 0.3s;
        }

        .settings-tab.active {
            color: #4f46e5;
            border-bottom-color: #4f46e5;
        }

        .settings-tab:hover {
            color: #4f46e5;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .info-box {
            background: #f0f9ff;
            border-left: 4px solid #3b82f6;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
        }

        .info-box i {
            color: #3b82f6;
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <?php include 'includes/super_admin_sidebar.php'; ?>
        
        <div class="main-content">
            <?php include 'includes/super_admin_header.php'; ?>
            
            <div class="dashboard-content">
                <div class="settings-container">
                    <h2><i class="fas fa-cog"></i> Settings</h2>

                    <?php if ($success_message): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($error_message): ?>
                        <div class="alert alert-error">
                            <i class="fas fa-exclamation-circle"></i> <?php echo $error_message; ?>
                        </div>
                    <?php endif; ?>

                    <div class="settings-tabs">
                        <button class="settings-tab active" onclick="switchTab('profile')">
                            <i class="fas fa-user"></i> Profile
                        </button>
                        <button class="settings-tab" onclick="switchTab('security')">
                            <i class="fas fa-lock"></i> Security
                        </button>
                        <button class="settings-tab" onclick="switchTab('system')">
                            <i class="fas fa-cogs"></i> System
                        </button>
                    </div>

                    <!-- Profile Tab -->
                    <div id="profile" class="tab-content active">
                        <div class="settings-card">
                            <h3><i class="fas fa-user-circle"></i> Profile Information</h3>
                            
                            <div class="profile-photo-section">
                                <div class="profile-photo-wrapper">
                                    <img src="<?php echo $photo; ?>" alt="Profile Photo" id="profileImage">
                                    <div class="photo-upload-overlay" onclick="togglePhotoUpload()">
                                        <i class="fas fa-camera"></i>
                                    </div>
                                </div>
                                <p style="color: #666; margin: 0; font-weight: 600;">Super Administrator</p>
                                
                                <!-- Photo Upload Form -->
                                <div class="photo-upload-form" id="photoUploadForm" style="display: none;">
                                    <h4 style="margin: 0 0 15px 0; color: #333;">
                                        <i class="fas fa-upload"></i> Upload Profile Photo
                                    </h4>
                                    <form method="POST" action="" enctype="multipart/form-data" id="uploadForm">
                                        <div class="file-input-wrapper">
                                            <input type="file" name="profile_photo" id="profilePhotoInput" accept="image/*" onchange="previewPhoto(event)">
                                            <label for="profilePhotoInput" class="file-input-label">
                                                <i class="fas fa-image"></i> Choose Photo
                                            </label>
                                        </div>
                                        
                                        <div class="file-preview" id="filePreview">
                                            <p style="margin: 0; color: #666;">
                                                <i class="fas fa-file-image"></i> 
                                                <span id="fileName"></span>
                                                <span id="fileSize" style="color: #999; font-size: 0.9em;"></span>
                                            </p>
                                        </div>
                                        
                                        <div>
                                            <button type="submit" name="upload_photo" class="btn-upload">
                                                <i class="fas fa-cloud-upload-alt"></i> Upload Photo
                                            </button>
                                            <button type="button" class="btn-primary" onclick="togglePhotoUpload()" style="background: #6b7280; margin-left: 10px;">
                                                <i class="fas fa-times"></i> Cancel
                                            </button>
                                        </div>
                                        <p style="margin: 15px 0 0 0; color: #999; font-size: 0.85em;">
                                            <i class="fas fa-info-circle"></i> Accepted formats: JPG, PNG, GIF (Max 5MB)
                                        </p>
                                    </form>
                                </div>
                            </div>

                            <form method="POST" action="">
                                <div class="form-group">
                                    <label><i class="fas fa-user"></i> Username</label>
                                    <input type="text" name="username" value="<?php echo $username; ?>" required>
                                </div>

                                <div class="form-group">
                                    <label><i class="fas fa-envelope"></i> Email Address</label>
                                    <input type="email" name="email" value="<?php echo $email; ?>" required>
                                </div>

                                <div class="form-group">
                                    <label><i class="fas fa-phone"></i> Phone Number</label>
                                    <input type="tel" name="phone_number" value="<?php echo $phone_number; ?>">
                                </div>

                                <button type="submit" name="update_profile" class="btn-primary">
                                    <i class="fas fa-save"></i> Update Profile
                                </button>
                            </form>
                        </div>
                    </div>

                    <!-- Security Tab -->
                    <div id="security" class="tab-content">
                        <div class="settings-card">
                            <h3><i class="fas fa-shield-alt"></i> Change Password</h3>
                            
                            <div class="info-box">
                                <i class="fas fa-info-circle"></i>
                                <strong>Password Requirements:</strong> Minimum 8 characters, including uppercase, lowercase, and numbers.
                            </div>

                            <form method="POST" action="">
                                <div class="form-group">
                                    <label><i class="fas fa-key"></i> Current Password</label>
                                    <input type="password" name="current_password" required>
                                </div>

                                <div class="form-group">
                                    <label><i class="fas fa-lock"></i> New Password</label>
                                    <input type="password" name="new_password" minlength="8" required>
                                </div>

                                <div class="form-group">
                                    <label><i class="fas fa-lock"></i> Confirm New Password</label>
                                    <input type="password" name="confirm_password" minlength="8" required>
                                </div>

                                <button type="submit" name="change_password" class="btn-primary">
                                    <i class="fas fa-key"></i> Change Password
                                </button>
                            </form>
                        </div>
                    </div>

                    <!-- System Tab -->
                    <div id="system" class="tab-content">
                        <div class="settings-card">
                            <h3><i class="fas fa-server"></i> System Settings</h3>
                            
                            <div style="display: grid; gap: 20px;">
                                <div style="background: #f9fafb; padding: 20px; border-radius: 8px; border-left: 4px solid #4f46e5;">
                                    <h4 style="margin: 0 0 10px 0; color: #333;"><i class="fas fa-database"></i> Database</h4>
                                    <p style="color: #666; margin: 10px 0;">Manage database backups and maintenance.</p>
                                    <a href="super_admin_backups.php" class="btn-primary" style="text-decoration: none; display: inline-block;">
                                        <i class="fas fa-external-link-alt"></i> Go to Backups
                                    </a>
                                </div>

                                <div style="background: #f9fafb; padding: 20px; border-radius: 8px; border-left: 4px solid #10b981;">
                                    <h4 style="margin: 0 0 10px 0; color: #333;"><i class="fas fa-cog"></i> System Configuration</h4>
                                    <p style="color: #666; margin: 10px 0;">Configure system-wide settings and preferences.</p>
                                    <button class="btn-primary" style="background: #10b981;" disabled>
                                        <i class="fas fa-wrench"></i> Coming Soon
                                    </button>
                                </div>

                                <div style="background: #f9fafb; padding: 20px; border-radius: 8px; border-left: 4px solid #f59e0b;">
                                    <h4 style="margin: 0 0 10px 0; color: #333;"><i class="fas fa-bell"></i> Notifications</h4>
                                    <p style="color: #666; margin: 10px 0;">Manage notification settings and preferences.</p>
                                    <button class="btn-primary" style="background: #f59e0b;" disabled>
                                        <i class="fas fa-cog"></i> Coming Soon
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <?php include 'includes/super_admin_mobile_nav.php'; ?>
    </div>

    <script>
        function togglePhotoUpload() {
            const uploadForm = document.getElementById('photoUploadForm');
            if (uploadForm.style.display === 'none') {
                uploadForm.style.display = 'block';
                uploadForm.classList.add('active');
            } else {
                uploadForm.style.display = 'none';
                uploadForm.classList.remove('active');
            }
        }

        function previewPhoto(event) {
            const file = event.target.files[0];
            if (file) {
                const fileName = file.name;
                const fileSize = (file.size / 1024 / 1024).toFixed(2); // Convert to MB
                
                document.getElementById('fileName').textContent = fileName;
                document.getElementById('fileSize').textContent = ` (${fileSize} MB)`;
                document.getElementById('filePreview').classList.add('active');
                
                // Preview the image
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('profileImage').src = e.target.result;
                };
                reader.readAsDataURL(file);
            }
        }

        function switchTab(tabName) {
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // Remove active from all tab buttons
            document.querySelectorAll('.settings-tab').forEach(btn => {
                btn.classList.remove('active');
            });
            
            // Show selected tab
            document.getElementById(tabName).classList.add('active');
            
            // Activate clicked button
            event.target.classList.add('active');
        }

        // Auto-hide alerts
        document.addEventListener('DOMContentLoaded', function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                setTimeout(function() {
                    alert.style.opacity = '0';
                    setTimeout(function() {
                        alert.remove();
                    }, 500);
                }, 5000);
            });
        });

        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const dashboardContainer = document.getElementById('dashboardContainer');
        
        if (menuToggle) {
            menuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('collapsed');
                dashboardContainer.classList.toggle('sidebar-collapsed');
            });
        }
    </script>
</body>
</html>
<?php
if (isset($conn) && $conn instanceof mysqli && $conn->ping()) {
    $conn->close();
}
?>