<?php
session_start();
require_once "../config/db.php";

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

$user_id = $_SESSION['user_id'];

/* ================================
   GET USER DATA
==================================*/
$stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE id=?");
mysqli_stmt_bind_param($stmt, "i", $user_id);
mysqli_stmt_execute($stmt);
$user = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));

/* ================================
   UPDATE PROFILE
==================================*/
$error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone_number']);

    // Check duplicate email (exclude self)
    $check = mysqli_prepare($conn, "SELECT id FROM users WHERE email=? AND id!=?");
    mysqli_stmt_bind_param($check, "si", $email, $user_id);
    mysqli_stmt_execute($check);
    mysqli_stmt_store_result($check);

    if(mysqli_stmt_num_rows($check) > 0){
        $error = "Email already exists.";
    } else {

        /* ===== PROFILE PICTURE UPLOAD ===== */
        if(!empty($_FILES['profile_pic']['name'])){
            $targetDir = "../assets/profile_pics/";
            $fileName = time() . "_" . basename($_FILES["profile_pic"]["name"]);
            $targetFile = $targetDir . $fileName;
            $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

            if(in_array($fileType, ['jpg','jpeg','png'])){
                if(move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $targetFile)){
                    if($user['profile_pic'] && file_exists($targetDir.$user['profile_pic'])){
                        unlink($targetDir.$user['profile_pic']);
                    }
                    mysqli_query($conn, "UPDATE users SET profile_pic='$fileName' WHERE id=$user_id");
                }
            } else {
                $error = "Only JPG, JPEG, PNG allowed.";
            }
        }

        if(empty($error)){
            $stmt = mysqli_prepare($conn, "UPDATE users SET full_name=?, email=?, phone_number=? WHERE id=?");
            mysqli_stmt_bind_param($stmt, "sssi", $full_name, $email, $phone, $user_id);
            mysqli_stmt_execute($stmt);
            header("Location: edit_profile.php?success=1");
            exit();
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Profile - QRCareTrack</title>
    <link rel="stylesheet" href="../assets/style.css">
    <link rel="stylesheet" href="../assets/settings.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
</head>
<body>

<?php include "../includes/sidebar.php"; ?>

<div class="main">
<h2>Edit My Profile</h2>

<div class="profile-edit-card">

    <!-- Avatar + Name + Role -->
    <div class="edit-header">
        <div class="avatar-wrapper">
        <?php 
        if($user['profile_pic']){
            echo "<img src='../assets/profile_pics/{$user['profile_pic']}' class='profile-img'>";
        } else {
            echo "<div class='avatar-placeholder-large'>". strtoupper($user['full_name'][0]) ."</div>";
        }
        ?>
        </div>
        <h3><?= htmlspecialchars($user['full_name']) ?></h3>
        <span class="badge badge-<?= strtolower($user['role']) ?>">
            <?= ucfirst($user['role']) ?>
        </span>
    </div>

    <?php if(isset($_GET['success'])): ?>
    <div class="alert success">Profile updated successfully.</div>
    <?php endif; ?>

    <?php if(!empty($error)): ?>
    <div class="alert error"><?= $error ?></div>
    <?php endif; ?>

    <!-- Form -->
    <form method="POST" enctype="multipart/form-data" class="styled-form">

        <div class="form-grid">
            <div class="form-group">
                <label>Full Name *</label>
                <input name="full_name" value="<?= htmlspecialchars($user['full_name']) ?>" required>
            </div>

            <div class="form-group">
                <label>Email *</label>
                <input type="email" name="email" value="<?= htmlspecialchars($user['email']) ?>" required>
            </div>

            <div class="form-group">
                <label>Phone Number</label>
                <input name="phone_number" value="<?= htmlspecialchars($user['phone_number']) ?>">
            </div>

            <div class="form-group">
                <label>Profile Picture</label>
                <input type="file" name="profile_pic" accept="image/png, image/jpeg">
                <small>Max 2MB. JPG / PNG only.</small>
            </div>
        </div>

        <!-- Read-only info -->
        <div class="readonly-box">
            <div><strong>Role:</strong> <?= ucfirst($user['role']) ?></div>
            <div><strong>Department ID:</strong> <?= $user['department_id'] ?? '-' ?></div>
        </div>

        <div class="form-actions">
            <a href="../settings.php" class="btn cancel">Cancel</a>
            <button type="submit" class="btn-save">
                <i class="fas fa-save"></i> Save Changes
            </button>
        </div>

    </form>
</div>

</div>
</body>
</html>