<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

require_once 'config.php';
$conn = getDBConnection();
$userId = (int) $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    $action = $_POST['action'] ?? '';

    if ($action === 'update_profile') {
        $full_name = trim($_POST['full_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');

        if ($full_name === '' || $email === '') {
            echo json_encode(['success' => false, 'message' => 'Full name and email are required']);
            exit;
        }

        $stmt = $conn->prepare("UPDATE users SET full_name = ?, email = ?, phone = ? WHERE id = ?");
        $stmt->bind_param('sssi', $full_name, $email, $phone, $userId);
        $success = $stmt->execute();
        $error = $stmt->error;
        $stmt->close();

        if ($success) {
            $_SESSION['full_name'] = $full_name;
            logActivity($conn, $userId, 'Update Profile', 'Updated profile details');
            echo json_encode(['success' => true, 'message' => 'Profile updated successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => $error ?: 'Failed to update profile']);
        }
        exit;
    }

    if ($action === 'change_password') {
        $current_password = $_POST['current_password'] ?? '';
        $new_password = $_POST['new_password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';

        if ($current_password === '' || $new_password === '' || $confirm_password === '') {
            echo json_encode(['success' => false, 'message' => 'All password fields are required']);
            exit;
        }

        if ($new_password !== $confirm_password) {
            echo json_encode(['success' => false, 'message' => 'New password and confirmation do not match']);
            exit;
        }

        $stmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();
        $stmt->close();

        $validPassword = $user && (password_verify($current_password, $user['password']) || $user['password'] === md5($current_password));
        if (!$validPassword) {
            echo json_encode(['success' => false, 'message' => 'Current password is incorrect']);
            exit;
        }

        $hashed = password_hash($new_password, PASSWORD_DEFAULT);
        $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
        $stmt->bind_param('si', $hashed, $userId);
        $success = $stmt->execute();
        $error = $stmt->error;
        $stmt->close();

        if ($success) {
            logActivity($conn, $userId, 'Change Password', 'Changed account password');
            echo json_encode(['success' => true, 'message' => 'Password changed successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => $error ?: 'Failed to change password']);
        }
        exit;
    }

    if ($action === 'upload_photo') {
        if (!isset($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
            echo json_encode(['success' => false, 'message' => 'Please select a valid image file']);
            exit;
        }

        if ($_FILES['photo']['size'] > 2 * 1024 * 1024) {
            echo json_encode(['success' => false, 'message' => 'Profile photo must be 2MB or smaller']);
            exit;
        }

        $extension = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'webp'];
        if (!in_array($extension, $allowed, true)) {
            echo json_encode(['success' => false, 'message' => 'Only JPG, PNG, and WEBP files are allowed']);
            exit;
        }

        $uploadDir = 'uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $storedExtension = $extension === 'jpeg' ? 'jpg' : $extension;
        $photoPath = $uploadDir . 'user_' . $userId . '.' . $storedExtension;
        if (!move_uploaded_file($_FILES['photo']['tmp_name'], $photoPath)) {
            echo json_encode(['success' => false, 'message' => 'Failed to save uploaded photo']);
            exit;
        }

        $stmt = $conn->prepare("UPDATE users SET photo = ? WHERE id = ?");
        $stmt->bind_param('si', $photoPath, $userId);
        $success = $stmt->execute();
        $error = $stmt->error;
        $stmt->close();

        if ($success) {
            logActivity($conn, $userId, 'Upload Photo', 'Updated profile photo');
            echo json_encode(['success' => true, 'message' => 'Profile photo updated', 'photo' => $photoPath]);
        } else {
            echo json_encode(['success' => false, 'message' => $error ?: 'Failed to update profile photo']);
        }
        exit;
    }

    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    exit;
}

$stmt = $conn->prepare("SELECT id, username, full_name, email, phone, role, photo FROM users WHERE id = ?");
$stmt->bind_param('i', $userId);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

$activities = [];
$stmt = $conn->prepare(
    "SELECT action, COALESCE(description, details, '') AS activity_details, ip_address, created_at
     FROM user_activities
     WHERE user_id = ?
     ORDER BY created_at DESC
     LIMIT 20"
);
$stmt->bind_param('i', $userId);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $activities[] = $row;
}
$stmt->close();
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile - EduTrack PRO</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="wrapper">
        <nav id="sidebar" class="sidebar">
        <?php echo buildSidebar(basename($_SERVER['PHP_SELF'])); ?>
        </nav>

        <div class="main-content">
            <header class="header">
                <button class="btn-toggle" id="sidebarToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="header-right">
                    <div class="dropdown">
                        <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars($_SESSION['full_name']); ?>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="profile.php"><i class="fas fa-user me-2"></i>Profile</a></li>
                            <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                        </ul>
                    </div>
                </div>
            </header>

            <main class="content">
                <div class="content-header">
                    <h2><i class="fas fa-user-circle me-2"></i>Profile</h2>
                    <p>Manage your account information, password, and recent activity.</p>
                </div>

                <div id="profileAlert" class="alert d-none" role="alert"></div>

                <div class="row">
                    <div class="col-lg-4">
                        <div class="settings-section">
                            <h5><i class="fas fa-id-badge me-2"></i>Profile Overview</h5>
                            <div class="text-center mb-4">
                                <?php if (!empty($user['photo']) && file_exists($user['photo'])): ?>
                                    <img src="<?php echo htmlspecialchars($user['photo']); ?>" alt="Profile Photo" class="img-thumbnail rounded-circle mb-3" style="width: 160px; height: 160px; object-fit: cover;">
                                <?php else: ?>
                                    <div class="d-inline-flex align-items-center justify-content-center rounded-circle bg-light border mb-3" style="width: 160px; height: 160px;">
                                        <i class="fas fa-user fa-4x text-secondary"></i>
                                    </div>
                                <?php endif; ?>
                                <h5 class="mb-1"><?php echo htmlspecialchars($user['full_name']); ?></h5>
                                <p class="text-muted mb-0"><?php echo htmlspecialchars($user['role']); ?></p>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Full Name</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['full_name']); ?>" disabled>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Email</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['email']); ?>" disabled>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Phone</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" disabled>
                            </div>
                            <div class="mb-0">
                                <label class="form-label">Role</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars(ucfirst($user['role'])); ?>" disabled>
                            </div>
                        </div>

                        <div class="settings-section mt-4">
                            <h5><i class="fas fa-camera me-2"></i>Profile Photo</h5>
                            <form id="photoForm" enctype="multipart/form-data">
                                <input type="hidden" name="action" value="upload_photo">
                                <div class="mb-3">
                                    <label class="form-label">Upload Photo</label>
                                    <input type="file" class="form-control" name="photo" accept=".jpg,.jpeg,.png,.webp" required>
                                    <small class="text-muted">JPG, PNG, or WEBP up to 2MB.</small>
                                </div>
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-upload me-2"></i>Upload Photo
                                </button>
                            </form>
                        </div>
                    </div>

                    <div class="col-lg-8">
                        <div class="settings-section">
                            <h5><i class="fas fa-user-edit me-2"></i>Edit Profile</h5>
                            <form id="profileForm">
                                <input type="hidden" name="action" value="update_profile">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Full Name</label>
                                        <input type="text" class="form-control" name="full_name" value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Email</label>
                                        <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Phone</label>
                                    <input type="text" class="form-control" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                                </div>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save me-2"></i>Save Profile
                                </button>
                            </form>
                        </div>

                        <div class="settings-section mt-4">
                            <h5><i class="fas fa-lock me-2"></i>Change Password</h5>
                            <form id="passwordForm">
                                <input type="hidden" name="action" value="change_password">
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Current Password</label>
                                        <input type="password" class="form-control" name="current_password" required>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">New Password</label>
                                        <input type="password" class="form-control" name="new_password" required>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Confirm Password</label>
                                        <input type="password" class="form-control" name="confirm_password" required>
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-warning">
                                    <i class="fas fa-key me-2"></i>Change Password
                                </button>
                            </form>
                        </div>

                        <div class="settings-section mt-4">
                            <h5><i class="fas fa-history me-2"></i>Recent Activity</h5>
                            <div class="table-responsive">
                                <table class="table table-hover" id="activityTable">
                                    <thead>
                                        <tr>
                                            <th>Date/Time</th>
                                            <th>Action</th>
                                            <th>Details</th>
                                            <th>IP Address</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($activities as $activity): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars(date('d M Y H:i:s', strtotime($activity['created_at']))); ?></td>
                                            <td><?php echo htmlspecialchars($activity['action']); ?></td>
                                            <td><?php echo htmlspecialchars($activity['activity_details']); ?></td>
                                            <td><?php echo htmlspecialchars($activity['ip_address'] ?: '-'); ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </main>

            <footer class="footer">
                <p>&copy; 2024 EduTrack PRO. All rights reserved.</p>
            </footer>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="js/main.js"></script>
    <script>
        function showAlert(type, message) {
            const alertBox = $('#profileAlert');
            alertBox.removeClass('d-none alert-success alert-danger').addClass(`alert-${type}`).text(message);
        }

        function submitAjaxForm(formSelector, useFormData = false) {
            const form = $(formSelector)[0];
            const ajaxData = useFormData ? new FormData(form) : $(formSelector).serialize();

            return $.ajax({
                url: 'profile.php',
                type: 'POST',
                data: ajaxData,
                processData: !useFormData,
                contentType: useFormData ? false : 'application/x-www-form-urlencoded; charset=UTF-8',
                dataType: 'json'
            });
        }

        $('#activityTable').DataTable({
            order: [[0, 'desc']]
        });

        $('#profileForm').on('submit', function(e) {
            e.preventDefault();
            submitAjaxForm('#profileForm').done(function(response) {
                showAlert(response.success ? 'success' : 'danger', response.message);
                if (response.success) {
                    window.setTimeout(function() {
                        window.location.reload();
                    }, 800);
                }
            }).fail(function() {
                showAlert('danger', 'Failed to update profile');
            });
        });

        $('#passwordForm').on('submit', function(e) {
            e.preventDefault();
            submitAjaxForm('#passwordForm').done(function(response) {
                showAlert(response.success ? 'success' : 'danger', response.message);
                if (response.success) {
                    $('#passwordForm')[0].reset();
                }
            }).fail(function() {
                showAlert('danger', 'Failed to change password');
            });
        });

        $('#photoForm').on('submit', function(e) {
            e.preventDefault();
            submitAjaxForm('#photoForm', true).done(function(response) {
                showAlert(response.success ? 'success' : 'danger', response.message);
                if (response.success) {
                    window.setTimeout(function() {
                        window.location.reload();
                    }, 800);
                }
            }).fail(function() {
                showAlert('danger', 'Failed to upload profile photo');
            });
        });
    </script>
</body>
</html>
