<?php
/**
 * User Profile
 * Common profile page for all users
 * Kenyan Pension & Life Insurance Management System
 */

require_once 'layouts/main.php';
require_once 'includes/auth.php';

requireLogin();

$user_id = $_SESSION['user_id'];
$message = '';
$messageType = '';

// Get user details
$user = $conn->query("SELECT u.*, r.role_name FROM users u INNER JOIN roles r ON u.role_id = r.role_id WHERE u.user_id = $user_id AND u.deleted_at IS NULL")->fetch_assoc();

if (!$user) {
    header('Location: logout.php');
    exit();
}

$profile = json_decode($user['profile'] ?? '{}', true);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Update profile information
    $first_name = $_POST['first_name'] ?? '';
    $last_name = $_POST['last_name'] ?? '';
    $phone = $_POST['phone'] ?? '';
    
    $updated_profile = json_encode([
        'first_name' => $first_name,
        'last_name' => $last_name,
        'phone' => $phone
    ]);
    
    $sql = "UPDATE users SET 
           email = ?,
           phone = ?,
           profile = ?,
           updated_at = CURRENT_TIMESTAMP
           WHERE user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssi",
        $_POST['email'],
        $phone,
        $updated_profile,
        $user_id
    );
    
    if ($stmt->execute()) {
        $message = 'Profile updated successfully';
        $messageType = 'success';
        // Refresh user data
        $user = $conn->query("SELECT u.*, r.role_name FROM users u INNER JOIN roles r ON u.role_id = r.role_id WHERE u.user_id = $user_id AND u.deleted_at IS NULL")->fetch_assoc();
        $profile = json_decode($user['profile'] ?? '{}', true);
    } else {
        $message = 'Failed to update profile';
        $messageType = 'danger';
    }
}

$pageTitle = 'My Profile';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Profile')); ?>
    <link rel="stylesheet" href="assets/css/pension-dashboard.css">
    <?php include 'layouts/head-css.php'; ?>
</head>

<body data-sidebar="dark">
    <div id="layout-wrapper">
        <?php include 'layouts/sidebar.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="welcome-header" style="background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>My Profile</h2>
                                <p>Manage your account information</p>
                            </div>
                        </div>
                    </div>

                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Account Information</h4>
                                </div>
                                <div class="page-card-body">
                                    <table class="table table-borderless">
                                        <tr>
                                            <td><strong>Username:</strong></td>
                                            <td><?php echo htmlspecialchars($user['username']); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Role:</strong></td>
                                            <td><span class="badge bg-info"><?php echo htmlspecialchars($user['role_name']); ?></span></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Last Login:</strong></td>
                                            <td><?php echo $user['last_login'] ? date('d M Y, h:i A', strtotime($user['last_login'])) : 'Never'; ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Account Status:</strong></td>
                                            <td>
                                                <span class="status-badge status-<?php echo $user['is_active'] ? 'active' : 'pending'; ?>">
                                                    <?php echo $user['is_active'] ? 'Active' : 'Inactive'; ?>
                                                </span>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Update Profile</h4>
                                </div>
                                <div class="page-card-body">
                                    <form method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">First Name</label>
                                            <input type="text" name="first_name" class="form-control" 
                                                   value="<?php echo htmlspecialchars($profile['first_name'] ?? ''); ?>">
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Last Name</label>
                                            <input type="text" name="last_name" class="form-control" 
                                                   value="<?php echo htmlspecialchars($profile['last_name'] ?? ''); ?>">
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Email</label>
                                            <input type="email" name="email" class="form-control" 
                                                   value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>" required>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Phone</label>
                                            <input type="text" name="phone" class="form-control" 
                                                   value="<?php echo htmlspecialchars($user['phone'] ?? $profile['phone'] ?? ''); ?>">
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary">
                                            <i class="ri-save-line me-2"></i>Update Profile
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
