<?php
require_once 'config/database.php';
requireAdmin();

// Get current admin data
$admin_id = $_SESSION['admin_id'];

try {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT * FROM admins WHERE id = ?");
    $stmt->execute([$admin_id]);
    $admin = $stmt->fetch();

    if (!$admin) {
        // Redirect if admin not found (session might be invalid)
        header('Location: login.php');
        exit;
    }
} catch (Exception $e) {
    $error = "Error loading profile data: " . $e->getMessage();
}

// Handle profile update
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    try {
        // Get form data
        $first_name = trim($_POST['first_name']);
        $last_name = trim($_POST['last_name']);
        $nickname = trim($_POST['nickname']);
        $email = trim($_POST['email']);
        $phone = trim($_POST['phone']);
        $college = trim($_POST['college']);
        $course = trim($_POST['course']);
        $year_of_study = intval($_POST['year_of_study']);
        
        // Validate email uniqueness (excluding current admin)
        $stmt = $pdo->prepare("SELECT id FROM admins WHERE email = ? AND id != ?");
        $stmt->execute([$email, $admin_id]);
        if ($stmt->rowCount() > 0) {
            throw new Exception("Email address is already in use by another admin.");
        }
        
        // Update admin profile
        $stmt = $pdo->prepare("
            UPDATE admins SET 
                first_name = ?, 
                last_name = ?, 
                nickname = ?, 
                email = ?, 
                phone = ?, 
                college = ?, 
                course = ?, 
                year_of_study = ?,
                updated_at = NOW()
            WHERE id = ?
        ");
        
        $stmt->execute([
            $first_name, 
            $last_name, 
            $nickname, 
            $email, 
            $phone, 
            $college, 
            $course, 
            $year_of_study,
            $admin_id
        ]);
        
        // Log activity
        logActivity($admin_id, 'profile_update', 'Profile information updated');
        
        // Update session data
        $_SESSION['admin_name'] = $first_name . ' ' . $last_name;
        
        // Refresh admin data
        $stmt = $pdo->prepare("SELECT * FROM admins WHERE id = ?");
        $stmt->execute([$admin_id]);
        $admin = $stmt->fetch();
        
        $success_message = "Profile updated successfully";
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Handle password change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    try {
        $current_password = $_POST['current_password'];
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];
        
        // Verify current password
        if (!password_verify($current_password, $admin['password_hash'])) {
            throw new Exception("Current password is incorrect");
        }
        
        // Validate password match
        if ($new_password !== $confirm_password) {
            throw new Exception("New passwords do not match");
        }
        
        // Validate password strength
        if (strlen($new_password) < 8) {
            throw new Exception("Password must be at least 8 characters long");
        }
        
        if (!preg_match('/[A-Z]/', $new_password) || 
            !preg_match('/[a-z]/', $new_password) || 
            !preg_match('/[0-9]/', $new_password)) {
            throw new Exception("Password must contain at least one uppercase letter, one lowercase letter, and one number");
        }
        
        // Update password
        $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
        
        $stmt = $pdo->prepare("
            UPDATE admins SET 
                password_hash = ?, 
                updated_at = NOW() 
            WHERE id = ?
        ");
        
        $stmt->execute([$password_hash, $admin_id]);
        
        // Log activity
        logActivity($admin_id, 'password_change', 'Password changed successfully', 'high');
        
        $success_message = "Password changed successfully";
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Handle profile photo upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_photo'])) {
    try {
        if (!isset($_FILES['profile_photo']) || $_FILES['profile_photo']['error'] !== UPLOAD_ERR_OK) {
            throw new Exception("No file uploaded or upload error occurred");
        }
        
        $file = $_FILES['profile_photo'];
        
        // Validate file type
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        if (!in_array($file['type'], $allowed_types)) {
            throw new Exception("Only JPG, PNG, and GIF files are allowed");
        }
        
        // Validate file size (5MB max)
        if ($file['size'] > 5 * 1024 * 1024) {
            throw new Exception("File size must be less than 5MB");
        }
        
        // Create upload directory if it doesn't exist
        $upload_dir = 'uploads/admin_photos/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        // Generate unique filename
        $filename = 'admin_' . $admin_id . '_' . time() . '_' . basename($file['name']);
        $filepath = $upload_dir . $filename;
        
        // Move uploaded file
        if (!move_uploaded_file($file['tmp_name'], $filepath)) {
            throw new Exception("Failed to save uploaded file");
        }
        
        // Update admin photo URL in database
        $photo_url = $filepath;
        $stmt = $pdo->prepare("
            UPDATE admins SET 
                photo_url = ?, 
                updated_at = NOW() 
            WHERE id = ?
        ");
        
        $stmt->execute([$photo_url, $admin_id]);
        
        // Log activity
        logActivity($admin_id, 'photo_update', 'Profile photo updated');
        
        // Refresh admin data
        $stmt = $pdo->prepare("SELECT * FROM admins WHERE id = ?");
        $stmt->execute([$admin_id]);
        $admin = $stmt->fetch();
        
        $success_message = "Profile photo updated successfully";
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Include header, navbar, and sidebar
require_once 'templates/header.php';
?>

<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    
    <!-- Top Navbar -->
    <?php require_once 'templates/navbar.php'; ?>
    
    <!-- Sidebar -->
    <?php require_once 'templates/sidebar.php'; ?>
    
    <!-- Additional responsive styles for profile page -->
    <style>
        /* General responsive adjustments */
        @media (max-width: 767.98px) {
            .content-wrapper {
                padding-bottom: 60px; /* Add space for mobile navigation */
            }
            
            /* Make tab buttons more touch friendly */
            .nav-tabs .nav-link {
                padding: 0.75rem 0.5rem;
                font-size: 0.9rem;
                text-align: center;
            }
            
            /* Increase form control height for touch */
            .form-control {
                height: calc(2.25rem + 4px);
            }
            
            /* Improve card spacing */
            .card {
                margin-bottom: 1rem;
            }
            
            /* Adjust table for small screens */
            .table {
                font-size: 0.85rem;
            }
            
            /* Improve modal usability on mobile */
            .modal-dialog {
                margin: 0.5rem;
            }
        }
        
        /* Small phone optimizations */
        @media (max-width: 575.98px) {
            .card-body {
                padding: 1rem;
            }
            
            h3.profile-username {
                font-size: 1.5rem;
            }
            
            .nav-tabs .nav-link {
                padding: 0.5rem 0.25rem;
            }
        }
        
        /* High DPI displays */
        @media (min-width: 1200px) {
            .profile-user-img {
                box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
                transition: all 0.3s cubic-bezier(.25,.8,.25,1);
            }
            
            .profile-user-img:hover {
                box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
            }
        }
        
        /* Touch-friendly adjustments */
        .custom-file-label, .custom-file-input {
            cursor: pointer;
        }
        
        /* Helper classes */
        .btn-md-inline {
            display: inline-block;
        }
        
        /* Animation for smoother transitions */
        .tab-pane {
            transition: opacity 0.15s linear;
        }
        
        /* Improved accessibility for password fields */
        .toggle-password {
            cursor: pointer;
        }
    </style>
    
    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- Content Header -->
        <section class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1>My Profile</h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                            <li class="breadcrumb-item active">My Profile</li>
                        </ol>
                    </div>
                </div>
            </div>
        </section>
        
        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                <?php if ($success_message): ?>
                <div class="alert alert-success alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <h5><i class="icon fas fa-check"></i> Success!</h5>
                    <?php echo htmlspecialchars($success_message); ?>
                </div>
                <?php endif; ?>
                
                <?php if ($error_message): ?>
                <div class="alert alert-danger alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <h5><i class="icon fas fa-ban"></i> Error!</h5>
                    <?php echo htmlspecialchars($error_message); ?>
                </div>
                <?php endif; ?>
                
                <div class="row">
                    <div class="col-lg-4 col-md-5 col-sm-12">
                        <!-- Profile Image -->
                        <div class="card card-primary card-outline">
                            <div class="card-body box-profile">
                                <div class="text-center">
                                    <img class="profile-user-img img-fluid img-circle" 
                                         src="<?php echo !empty($admin['photo_url']) ? htmlspecialchars($admin['photo_url']) : 'dist/img/user-default.jpg'; ?>" 
                                         alt="Admin profile picture" style="width: 100px; height: 100px; object-fit: cover;">
                                </div>
                                
                                <h3 class="profile-username text-center">
                                    <?php echo htmlspecialchars($admin['first_name'] . ' ' . $admin['last_name']); ?>
                                </h3>
                                
                                <p class="text-muted text-center">
                                    <?php echo htmlspecialchars($admin['role']); ?>
                                </p>
                                
                                <ul class="list-group list-group-unbordered mb-3">
                                    <li class="list-group-item">
                                        <b>KSO ID</b> <span class="float-right text-truncate" style="max-width: 60%;"><?php echo htmlspecialchars($admin['kso_id']); ?></span>
                                    </li>
                                    <li class="list-group-item">
                                        <b>Username</b> <span class="float-right text-truncate" style="max-width: 60%;"><?php echo htmlspecialchars($admin['username']); ?></span>
                                    </li>
                                    <li class="list-group-item">
                                        <b>Status</b> 
                                        <span class="float-right">
                                            <span class="badge badge-<?php 
                                                echo $admin['status'] === 'active' ? 'success' : 
                                                    ($admin['status'] === 'inactive' ? 'secondary' : 
                                                    ($admin['status'] === 'pending' ? 'warning' : 'danger')); 
                                            ?>">
                                                <?php echo ucfirst(htmlspecialchars($admin['status'])); ?>
                                            </span>
                                        </span>
                                    </li>
                                    <li class="list-group-item">
                                        <b>Term</b> <span class="float-right text-truncate" style="max-width: 60%;">
                                            <?php echo htmlspecialchars($admin['term_from_year'] . ' - ' . $admin['term_to_year']); ?>
                                        </span>
                                    </li>
                                </ul>
                                
                                <!-- Photo Upload Button (Mobile) -->
                                <div class="d-block d-md-none mb-3">
                                    <button type="button" class="btn btn-primary btn-sm btn-block" data-toggle="modal" data-target="#photoUploadModal">
                                        <i class="fas fa-camera mr-1"></i> Change Photo
                                    </button>
                                </div>
                                
                                <!-- Photo Upload Form (Desktop) -->
                                <div class="d-none d-md-block">
                                    <form action="profile.php" method="post" enctype="multipart/form-data">
                                        <div class="form-group">
                                            <div class="custom-file">
                                                <input type="file" class="custom-file-input" id="profile_photo" name="profile_photo" required>
                                                <label class="custom-file-label" for="profile_photo">Choose new photo</label>
                                            </div>
                                            <small class="form-text text-muted">Max: 5MB. JPG, PNG, GIF</small>
                                        </div>
                                        <button type="submit" name="upload_photo" class="btn btn-primary btn-block">
                                            <i class="fas fa-upload mr-1"></i> Upload New Photo
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Last Login Information -->
                        <div class="card card-info">
                            <div class="card-header">
                                <h3 class="card-title">Account Information</h3>
                            </div>
                            <div class="card-body">
                                <strong><i class="fas fa-clock mr-1"></i> Last Login</strong>
                                <p class="text-muted">
                                    <?php echo !empty($admin['last_login']) ? date('F j, Y, g:i a', strtotime($admin['last_login'])) : 'Never'; ?>
                                </p>
                                <hr>
                                <strong><i class="fas fa-calendar-plus mr-1"></i> Account Created</strong>
                                <p class="text-muted">
                                    <?php echo date('F j, Y', strtotime($admin['created_at'])); ?>
                                </p>
                                <hr>
                                <strong><i class="fas fa-calendar-check mr-1"></i> Last Updated</strong>
                                <p class="text-muted">
                                    <?php echo date('F j, Y, g:i a', strtotime($admin['updated_at'])); ?>
                                </p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-8 col-md-7 col-sm-12">
                        <div class="card card-primary card-outline card-tabs">
                            <div class="card-header p-0 pt-1 border-bottom-0">
                                <ul class="nav nav-tabs" id="profile-tabs" role="tablist">
                                    <li class="nav-item">
                                        <a class="nav-link active" id="profile-info-tab" data-toggle="pill" href="#profile-info" role="tab" aria-controls="profile-info" aria-selected="true">
                                            <i class="fas fa-user mr-1"></i> <span class="d-none d-md-inline">Profile Information</span><span class="d-md-none">Profile</span>
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" id="change-password-tab" data-toggle="pill" href="#change-password" role="tab" aria-controls="change-password" aria-selected="false">
                                            <i class="fas fa-key mr-1"></i> <span class="d-none d-md-inline">Change Password</span><span class="d-md-none">Password</span>
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" id="account-activity-tab" data-toggle="pill" href="#account-activity" role="tab" aria-controls="account-activity" aria-selected="false">
                                            <i class="fas fa-history mr-1"></i> <span class="d-none d-md-inline">Account Activity</span><span class="d-md-none">Activity</span>
                                        </a>
                                    </li>
                                </ul>
                            </div>
                            
                            <div class="card-body">
                                <div class="tab-content" id="profile-tabs-content">
                                    <!-- Profile Information Tab -->
                                    <div class="tab-pane fade show active" id="profile-info" role="tabpanel" aria-labelledby="profile-info-tab">
                                        <form action="profile.php" method="post">
                                            <div class="row">
                                                <div class="col-md-6 col-sm-12">
                                                    <div class="form-group">
                                                        <label for="first_name">First Name</label>
                                                        <input type="text" class="form-control" id="first_name" name="first_name" value="<?php echo htmlspecialchars($admin['first_name']); ?>" required>
                                                    </div>
                                                </div>
                                                <div class="col-md-6 col-sm-12">
                                                    <div class="form-group">
                                                        <label for="last_name">Last Name</label>
                                                        <input type="text" class="form-control" id="last_name" name="last_name" value="<?php echo htmlspecialchars($admin['last_name']); ?>" required>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="nickname">Nickname</label>
                                                <input type="text" class="form-control" id="nickname" name="nickname" value="<?php echo htmlspecialchars($admin['nickname'] ?? ''); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="email">Email</label>
                                                <div class="input-group">
                                                    <div class="input-group-prepend">
                                                        <span class="input-group-text"><i class="fas fa-envelope"></i></span>
                                                    </div>
                                                    <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($admin['email']); ?>" required>
                                                </div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="phone">Phone Number</label>
                                                <div class="input-group">
                                                    <div class="input-group-prepend">
                                                        <span class="input-group-text"><i class="fas fa-phone"></i></span>
                                                    </div>
                                                    <input type="text" class="form-control" id="phone" name="phone" value="<?php echo htmlspecialchars($admin['phone'] ?? ''); ?>">
                                                </div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="college">College/Institution</label>
                                                <input type="text" class="form-control" id="college" name="college" value="<?php echo htmlspecialchars($admin['college'] ?? ''); ?>">
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 col-sm-12">
                                                    <div class="form-group">
                                                        <label for="course">Course/Program</label>
                                                        <input type="text" class="form-control" id="course" name="course" value="<?php echo htmlspecialchars($admin['course'] ?? ''); ?>">
                                                    </div>
                                                </div>
                                                <div class="col-md-6 col-sm-12">
                                                    <div class="form-group">
                                                        <label for="year_of_study">Year of Study</label>
                                                        <select class="form-control" id="year_of_study" name="year_of_study">
                                                            <option value="0">Select Year</option>
                                                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                                            <option value="<?php echo $i; ?>" <?php echo ($admin['year_of_study'] == $i) ? 'selected' : ''; ?>>
                                                                Year <?php echo $i; ?>
                                                            </option>
                                                            <?php endfor; ?>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <button type="submit" name="update_profile" class="btn btn-primary btn-block btn-md-inline">
                                                <i class="fas fa-save mr-1"></i> Save Changes
                                            </button>
                                        </form>
                                    </div>
                                    
                                    <!-- Change Password Tab -->
                                    <div class="tab-pane fade" id="change-password" role="tabpanel" aria-labelledby="change-password-tab">
                                        <form action="profile.php" method="post" id="passwordForm">
                                            <div class="form-group">
                                                <label for="current_password">Current Password</label>
                                                <div class="input-group">
                                                    <div class="input-group-prepend">
                                                        <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                                    </div>
                                                    <input type="password" class="form-control" id="current_password" name="current_password" required>
                                                    <div class="input-group-append">
                                                        <button class="btn btn-outline-secondary toggle-password" type="button" data-target="current_password">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="new_password">New Password</label>
                                                <div class="input-group">
                                                    <div class="input-group-prepend">
                                                        <span class="input-group-text"><i class="fas fa-key"></i></span>
                                                    </div>
                                                    <input type="password" class="form-control" id="new_password" name="new_password" required>
                                                    <div class="input-group-append">
                                                        <button class="btn btn-outline-secondary toggle-password" type="button" data-target="new_password">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                                <small class="form-text text-muted">
                                                    <i class="fas fa-info-circle mr-1"></i> Password must be at least 8 characters long and include uppercase letters, lowercase letters, and numbers.
                                                </small>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="confirm_password">Confirm New Password</label>
                                                <div class="input-group">
                                                    <div class="input-group-prepend">
                                                        <span class="input-group-text"><i class="fas fa-key"></i></span>
                                                    </div>
                                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                                    <div class="input-group-append">
                                                        <button class="btn btn-outline-secondary toggle-password" type="button" data-target="confirm_password">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="password-strength-meter mt-3 mb-3 d-none" id="password-strength-meter">
                                                <p class="mb-1">Password Strength: <span id="password-strength-text">Not Set</span></p>
                                                <div class="progress" style="height: 6px;">
                                                    <div id="password-strength-bar" class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                                                </div>
                                            </div>
                                            
                                            <button type="submit" name="change_password" class="btn btn-danger btn-block btn-md-inline">
                                                <i class="fas fa-key mr-1"></i> Change Password
                                            </button>
                                        </form>
                                    </div>
                                    
                                    <!-- Account Activity Tab -->
                                    <div class="tab-pane fade" id="account-activity" role="tabpanel" aria-labelledby="account-activity-tab">
                                        <div class="card card-outline card-info mb-3 d-block d-md-none">
                                            <div class="card-body p-2">
                                                <div class="text-muted">
                                                    <i class="fas fa-info-circle mr-1"></i> Swipe horizontally to see more details in the activity table.
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="table-responsive">
                                            <table class="table table-striped table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Activity</th>
                                                        <th>Details</th>
                                                        <th>IP Address</th>
                                                        <th>Date/Time</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    // Get activity logs for current admin
                                                    try {
                                                        $stmt = $pdo->prepare("
                                                            SELECT * FROM activity_logs 
                                                            WHERE user_id = ? 
                                                            ORDER BY created_at DESC 
                                                            LIMIT 20
                                                        ");
                                                        $stmt->execute([$admin_id]);
                                                        $logs = $stmt->fetchAll();
                                                        
                                                        if (count($logs) > 0) {
                                                            foreach ($logs as $log) {
                                                                echo '<tr>';
                                                                echo '<td>' . htmlspecialchars(ucwords(str_replace('_', ' ', $log['action']))) . '</td>';
                                                                echo '<td>' . htmlspecialchars($log['details'] ?? 'N/A') . '</td>';
                                                                echo '<td>' . htmlspecialchars($log['ip_address']) . '</td>';
                                                                echo '<td>' . date('M j, Y g:i a', strtotime($log['created_at'])) . '</td>';
                                                                echo '</tr>';
                                                            }
                                                        } else {
                                                            echo '<tr><td colspan="4" class="text-center">No activity logs found</td></tr>';
                                                        }
                                                    } catch (Exception $e) {
                                                        echo '<tr><td colspan="4" class="text-center">Error loading activity logs: ' . $e->getMessage() . '</td></tr>';
                                                    }
                                                    ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
    
    <!-- Footer -->
    <?php require_once 'templates/footer.php'; ?>
</div>

<!-- JavaScript for profile page -->
<script>
$(document).ready(function() {
    // Initialize custom file input
    bsCustomFileInput.init();
    
    // Validate password form
    $('#passwordForm').on('submit', function(e) {
        const newPassword = $('#new_password').val();
        const confirmPassword = $('#confirm_password').val();
        
        // Check password match
        if (newPassword !== confirmPassword) {
            e.preventDefault();
            Swal.fire({
                icon: 'error',
                title: 'Passwords Do Not Match',
                text: 'Please make sure your passwords match.',
                confirmButtonColor: '#3085d6'
            });
            return false;
        }
        
        // Check password strength
        if (newPassword.length < 8) {
            e.preventDefault();
            Swal.fire({
                icon: 'error',
                title: 'Password Too Short',
                text: 'Password must be at least 8 characters long.',
                confirmButtonColor: '#3085d6'
            });
            return false;
        }
        
        const hasUppercase = /[A-Z]/.test(newPassword);
        const hasLowercase = /[a-z]/.test(newPassword);
        const hasNumbers = /[0-9]/.test(newPassword);
        
        if (!hasUppercase || !hasLowercase || !hasNumbers) {
            e.preventDefault();
            Swal.fire({
                icon: 'error',
                title: 'Password Too Weak',
                text: 'Password must contain at least one uppercase letter, one lowercase letter, and one number.',
                confirmButtonColor: '#3085d6'
            });
            return false;
        }
        
        return true;
    });

    // Custom Tab JS for Mobile
    $(function() {
        // Handle tab selection on mobile through touch events
        const tabLinks = document.querySelectorAll('#profile-tabs .nav-link');
        const mediaQuery = window.matchMedia('(max-width: 767px)');
        
        function handleTabInteraction() {
            if (mediaQuery.matches) {
                // For mobile: Show full width tabs with touch-friendly targets
                document.querySelectorAll('.nav-tabs .nav-item').forEach(item => {
                    item.style.width = (100 / tabLinks.length) + '%';
                });
            }
        }
        
        // Initial call
        handleTabInteraction();
        
        // Handle resize events
        window.addEventListener('resize', handleTabInteraction);
    });
});
});
</script>

<!-- Photo Upload Modal for Mobile -->
<div class="modal fade" id="photoUploadModal" tabindex="-1" role="dialog" aria-labelledby="photoUploadModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="photoUploadModalLabel">Upload Profile Photo</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form action="profile.php" method="post" enctype="multipart/form-data" id="mobilePhotoForm">
                    <div class="text-center mb-3">
                        <img id="photoPreview" src="<?php echo !empty($admin['photo_url']) ? htmlspecialchars($admin['photo_url']) : 'dist/img/user-default.jpg'; ?>" 
                             alt="Photo preview" class="img-fluid img-circle" style="width: 150px; height: 150px; object-fit: cover;">
                    </div>
                    <div class="form-group">
                        <div class="custom-file">
                            <input type="file" class="custom-file-input" id="mobile_profile_photo" name="profile_photo" required>
                            <label class="custom-file-label" for="mobile_profile_photo">Choose photo</label>
                        </div>
                        <small class="form-text text-muted">Max size: 5MB. Formats: JPG, PNG, GIF</small>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="submit" form="mobilePhotoForm" name="upload_photo" class="btn btn-primary">
                    <i class="fas fa-upload mr-1"></i> Upload Photo
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Additional responsive scripts -->
<script>
    // Preview image before upload
    $(document).ready(function() {
        function readURL(input, previewId) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    $(previewId).attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
        
        // Handle desktop photo preview
        $("#profile_photo").change(function() {
            readURL(this, '#photoPreview');
        });
        
        // Handle mobile photo preview
        $("#mobile_profile_photo").change(function() {
            readURL(this, '#photoPreview');
            var fileName = $(this).val().split('\\').pop();
            $(this).next('.custom-file-label').addClass("selected").html(fileName);
        });
        
        // Password toggle visibility
        $('.toggle-password').click(function() {
            const targetId = $(this).data('target');
            const inputField = $('#' + targetId);
            const icon = $(this).find('i');
            
            if (inputField.attr('type') === 'password') {
                inputField.attr('type', 'text');
                icon.removeClass('fa-eye').addClass('fa-eye-slash');
            } else {
                inputField.attr('type', 'password');
                icon.removeClass('fa-eye-slash').addClass('fa-eye');
            }
        });
        
        // Password strength meter
        $('#new_password').on('input', function() {
            const password = $(this).val();
            let strength = 0;
            let strengthText = '';
            let barClass = '';
            
            if (password.length === 0) {
                $('#password-strength-meter').addClass('d-none');
                return;
            } else {
                $('#password-strength-meter').removeClass('d-none');
            }
            
            // Length check
            if (password.length >= 8) strength += 20;
            
            // Character type checks
            if (password.match(/[a-z]+/)) strength += 20;
            if (password.match(/[A-Z]+/)) strength += 20;
            if (password.match(/[0-9]+/)) strength += 20;
            if (password.match(/[^a-zA-Z0-9]+/)) strength += 20;
            
            // Set text and color based on strength
            if (strength <= 20) {
                strengthText = 'Very Weak';
                barClass = 'bg-danger';
            } else if (strength <= 40) {
                strengthText = 'Weak';
                barClass = 'bg-warning';
            } else if (strength <= 60) {
                strengthText = 'Medium';
                barClass = 'bg-info';
            } else if (strength <= 80) {
                strengthText = 'Strong';
                barClass = 'bg-primary';
            } else {
                strengthText = 'Very Strong';
                barClass = 'bg-success';
            }
            
            $('#password-strength-text').text(strengthText);
            $('#password-strength-bar')
                .attr('aria-valuenow', strength)
                .css('width', strength + '%')
                .removeClass('bg-danger bg-warning bg-info bg-primary bg-success')
                .addClass(barClass);
        });
        
        // CSS class for responsive buttons
        // On mobile: full width, on desktop: normal width
        $(window).on('resize', function() {
            if ($(window).width() < 768) {
                $('.btn-md-inline').addClass('btn-block');
            } else {
                $('.btn-md-inline').removeClass('btn-block');
            }
        }).trigger('resize');
    });
</script>

</body>
</html>
