<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin ID from URL (for viewing other admins) or use current admin
$admin_id = $_GET['id'] ?? $_SESSION['user_id'];

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email, u.last_login, u.is_active,
                      JSON_UNQUOTE(JSON_EXTRACT(a.permissions, '$')) as permissions_text
                      FROM admins a
                      JOIN users u ON a.id = u.id
                      WHERE a.id = ?");
$stmt->execute([$admin_id]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

// Check if viewing own profile
$is_own_profile = ($admin_id == $_SESSION['user_id']);

$error = '';
$success = '';
$upload_dir = 'uploads/admins/';

// Create upload directory if it doesn't exist
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $department = $_POST['department'] ?? '';
    $position = $_POST['position'] ?? '';
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // Validate form data
    if (empty($first_name) || empty($last_name)) {
        $error = "First name and last name are required.";
    } else {
        try {
            // Start transaction
            $pdo->beginTransaction();
            
            // Handle profile photo upload
            $profile_photo = $admin['profile_photo'];
            if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['name']) {
                $file_name = $_FILES['profile_photo']['name'];
                $file_tmp = $_FILES['profile_photo']['tmp_name'];
                $file_size = $_FILES['profile_photo']['size'];
                $file_error = $_FILES['profile_photo']['error'];
                
                if ($file_error === UPLOAD_ERR_OK && $file_size <= 5 * 1024 * 1024) {
                    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                    $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];
                    
                    if (in_array($file_ext, $allowed_exts)) {
                        $unique_name = $admin_id . '_admin_' . time() . '.' . $file_ext;
                        $file_path = $upload_dir . $unique_name;
                        
                        if (move_uploaded_file($file_tmp, $file_path)) {
                            // Remove old photo if it exists and is not the default
                            if ($admin['profile_photo'] && $admin['profile_photo'] !== 'img/profile-placeholder.jpg' && file_exists($admin['profile_photo'])) {
                                unlink($admin['profile_photo']);
                            }
                            $profile_photo = $file_path;
                        }
                    } else {
                        $error = "File type not allowed. Please upload JPG, PNG, or GIF files.";
                    }
                } elseif ($file_error === UPLOAD_ERR_INI_SIZE || $file_error === UPLOAD_ERR_FORM_SIZE) {
                    $error = "File is too large. Maximum size is 5MB.";
                } else {
                    $error = "Error uploading file. Please try again.";
                }
            }
            
            // Update admin profile
            $stmt = $pdo->prepare("UPDATE admins SET 
                first_name = ?, last_name = ?, phone = ?, profile_photo = ?, 
                department = ?, position = ?, updated_at = NOW()
                WHERE id = ?");
            
            $stmt->execute([
                $first_name, $last_name, $phone, $profile_photo, 
                $department, $position, $admin_id
            ]);
            
            // Update password if provided
            if ($new_password) {
                if (empty($current_password)) {
                    $error = "Current password is required to change your password.";
                } else {
                    // Verify current password
                    $stmt = $pdo->prepare("SELECT password_hash FROM users WHERE id = ?");
                    $stmt->execute([$admin_id]);
                    $user = $stmt->fetch();
                    
                    if (!$user || !password_verify($current_password, $user['password_hash'])) {
                        $error = "Current password is incorrect.";
                    } elseif ($new_password !== $confirm_password) {
                        $error = "New passwords do not match.";
                    } elseif (strlen($new_password) < 6) {
                        $error = "New password must be at least 6 characters long.";
                    } else {
                        // Update password
                        $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
                        $pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?")
                            ->execute([$password_hash, $admin_id]);
                    }
                }
            }
            
            // If updating own profile, update session data
            if ($is_own_profile) {
                $_SESSION['first_name'] = $first_name;
                $_SESSION['last_name'] = $last_name;
                $_SESSION['profile_photo'] = $profile_photo;
            }
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "profile_updated",
                "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} updated profile for {$first_name} {$last_name}"
            ]);
            
            // Commit transaction
            $pdo->commit();
            
            $success = "Profile updated successfully!";
            
        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Failed to update profile. Please try again.";
        }
    }
}

// Get recent activities for this admin
$activities = $pdo->prepare("SELECT a.*, 
                           CASE 
                               WHEN a.activity_type = 'login' THEN 'Logged in'
                               WHEN a.activity_type = 'logout' THEN 'Logged out'
                               WHEN a.activity_type = 'profile_updated' THEN 'Updated profile'
                               WHEN a.activity_type = 'student_created' THEN 'Created student account'
                               WHEN a.activity_type = 'counselor_created' THEN 'Created counselor account'
                               WHEN a.activity_type = 'admin_created' THEN 'Created admin account'
                               WHEN a.activity_type = 'application_created' THEN 'Created application'
                               WHEN a.activity_type = 'payment_created' THEN 'Created payment'
                               ELSE a.activity_type
                           END as activity_description
                           FROM activities a
                           WHERE a.user_id = ?
                           ORDER BY a.created_at DESC LIMIT 10");
$activities->execute([$admin_id]);
$activities = $activities->fetchAll();

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title><?= htmlspecialchars($admin['first_name'] . ' ' . $admin['last_name']) ?> - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .profile-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0;
            padding: 30px;
        }
        .profile-img {
            width: 120px;
            height: 120px;
            object-fit: cover;
            border-radius: 50%;
            border: 5px solid white;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .section-card {
            border: 1px solid #eee;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .section-header {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            border-radius: 10px 10px 0 0;
            font-weight: 600;
        }
        .section-body {
            padding: 20px;
        }
        .info-item {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px dashed #eee;
        }
        .info-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        .info-label {
            font-weight: 600;
            color: #6c757d;
            margin-bottom: 5px;
        }
        .info-value {
            font-size: 1.1em;
        }
        .permissions-list {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
        }
        .permission-badge {
            background: #e9ecef;
            color: #495057;
            padding: 3px 8px;
            border-radius: 15px;
            font-size: 0.8em;
        }
        .activity-item {
            border-bottom: 1px solid #eee;
            padding: 15px 0;
        }
        .activity-item:last-child {
            border-bottom: none;
        }
        .profile-upload {
            position: relative;
            display: inline-block;
        }
        .upload-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: rgba(0,0,0,0.5);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: all 0.3s;
        }
        .profile-upload:hover .upload-overlay {
            opacity: 1;
        }
        .file-input {
            display: none;
        }
    </style>
</head>
<body>

<?php include 'admin-navbar.php'; ?>

<div class="container py-5">
    <div class="row">
        <div class="col-lg-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="display-5">Admin Profile</h1>
                <div>
                    <?php if ($is_own_profile): ?>
                    <a href="admin-dashboard.php" class="btn btn-outline-primary">Back to Dashboard</a>
                    <?php else: ?>
                    <a href="admin-manage-admins.php" class="btn btn-outline-primary">Back to Admins</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Profile Header -->
    <div class="profile-header text-center text-white mb-4">
        <div class="d-flex align-items-center justify-content-center mb-3">
            <div class="profile-upload">
                <img src="<?= htmlspecialchars($admin['profile_photo'] ?: 'img/profile-placeholder.jpg') ?>" 
                     alt="<?= htmlspecialchars($admin['first_name']) ?>" class="profile-img">
                <div class="upload-overlay">
                    <i class="fas fa-camera"></i>
                </div>
                <?php if ($is_own_profile): ?>
                <input type="file" name="profile_photo" id="profilePhoto" class="file-input" accept="image/*">
                <?php endif; ?>
            </div>
        </div>
        <h2><?= htmlspecialchars($admin['first_name'] . ' ' . $admin['last_name']) ?></h2>
        <p class="lead mb-2"><?= htmlspecialchars($admin['email']) ?></p>
        <div class="d-flex justify-content-center align-items-center">
            <span class="mr-3">Position: <strong><?= htmlspecialchars($admin['position'] ?? 'Not specified') ?></strong></span>
            <span>Department: <strong><?= htmlspecialchars($admin['department'] ?? 'Not specified') ?></strong></span>
        </div>
    </div>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if (isset($success)): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <div class="row">
        <div class="col-lg-8">
            <!-- Profile Form -->
            <form method="POST" enctype="multipart/form-data">
                <div class="section-card">
                    <div class="section-header">Personal Information</div>
                    <div class="section-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label>First Name *</label>
                                <input type="text" name="first_name" class="form-control" 
                                       value="<?= htmlspecialchars($admin['first_name']) ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>Last Name *</label>
                                <input type="text" name="last_name" class="form-control" 
                                       value="<?= htmlspecialchars($admin['last_name']) ?>" required>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label>Email</label>
                                <input type="email" class="form-control" value="<?= htmlspecialchars($admin['email']) ?>" disabled>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>Phone</label>
                                <input type="text" name="phone" class="form-control" 
                                       value="<?= htmlspecialchars($admin['phone'] ?? '') ?>">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label>Department</label>
                                <select name="department" class="form-control">
                                    <option value="">Select Department</option>
                                    <option value="administration" <?= ($admin['department'] ?? '') === 'administration' ? 'selected' : '' ?>>Administration</option>
                                    <option value="admissions" <?= ($admin['department'] ?? '') === 'admissions' ? 'selected' : '' ?>>Admissions</option>
                                    <option value="finance" <?= ($admin['department'] ?? '') === 'finance' ? 'selected' : '' ?>>Finance</option>
                                    <option value="marketing" <?= ($admin['department'] ?? '') === 'marketing' ? 'selected' : '' ?>>Marketing</option>
                                    <option value="operations" <?= ($admin['department'] ?? '') === 'operations' ? 'selected' : '' ?>>Operations</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>Position</label>
                                <input type="text" name="position" class="form-control" 
                                       value="<?= htmlspecialchars($admin['position'] ?? '') ?>">
                            </div>
                        </div>
                    </div>
                </div>

                <?php if ($is_own_profile): ?>
                <div class="section-card">
                    <div class="section-header">Change Password</div>
                    <div class="section-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label>Current Password</label>
                                <input type="password" name="current_password" class="form-control">
                                <small class="form-text text-muted">Required to change password</small>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label>New Password</label>
                                <input type="password" name="new_password" class="form-control">
                                <small class="form-text text-muted">Leave blank to keep current password</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>Confirm New Password</label>
                                <input type="password" name="confirm_password" class="form-control">
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <div class="text-center">
                    <button type="submit" name="update_profile" class="btn btn-primary btn-lg px-5">Update Profile</button>
                </div>
            </form>
        </div>

        <div class="col-lg-4">
            <!-- Account Information -->
            <div class="section-card">
                <div class="section-header">Account Information</div>
                <div class="section-body">
                    <div class="info-item">
                        <div class="info-label">Account Status</div>
                        <div class="info-value">
                            <span class="status-badge <?= $admin['is_active'] ? 'status-active' : 'status-inactive' ?>">
                                <?= $admin['is_active'] ? 'Active' : 'Inactive' ?>
                            </span>
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Last Login</div>
                        <div class="info-value"><?= $admin['last_login'] ? date('M j, Y H:i', strtotime($admin['last_login'])) : 'Never' ?></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Created</div>
                        <div class="info-value"><?= date('M j, Y', strtotime($admin['created_at'])) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Last Updated</div>
                        <div class="info-value"><?= date('M j, Y', strtotime($admin['updated_at'])) ?></div>
                    </div>
                </div>
            </div>

            <!-- Permissions -->
            <div class="section-card">
                <div class="section-header">Permissions</div>
                <div class="section-body">
                    <div class="permissions-list">
                        <?php 
                        $permissions = json_decode($admin['permissions'] ?? '[]', true);
                        if ($permissions) {
                            foreach ($permissions as $permission) {
                                echo '<span class="permission-badge">' . ucfirst(str_replace('_', ' ', $permission)) . '</span>';
                            }
                        } else {
                            echo '<p class="text-muted">No specific permissions assigned</p>';
                        }
                        ?>
                    </div>
                </div>
            </div>

            <!-- Recent Activities -->
            <div class="section-card">
                <div class="section-header">Recent Activities</div>
                <div class="section-body">
                    <?php if (empty($activities)): ?>
                    <div class="text-center py-3">
                        <i class="fas fa-history fa-2x text-muted mb-3"></i>
                        <p class="text-muted small">No recent activities</p>
                    </div>
                    <?php else: ?>
                    <?php foreach ($activities as $act): ?>
                    <div class="activity-item">
                        <strong><?= htmlspecialchars($act['activity_description']) ?></strong>
                        <br>
                        <small class="text-muted">
                            <?= date('M j, H:i', strtotime($act['created_at'])) ?>
                        </small>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
    // Profile photo upload functionality
    document.getElementById('profilePhoto').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // Update preview
            const reader = new FileReader();
            reader.onload = function(e) {
                document.querySelector('.profile-img').src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
    
    // Allow clicking on the image to change photo
    document.querySelector('.profile-upload').addEventListener('click', function() {
        if (document.getElementById('profilePhoto')) {
            document.getElementById('profilePhoto').click();
        }
    });
</script>
</body>
</html>