<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
include 'config.php';

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

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

// Fetch user info
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
if (!$stmt) {
    die("Prepare failed (fetch user): " . $conn->error);
}
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

if (!$user) {
    $_SESSION['message'] = "User not found.";
    $_SESSION['message_type'] = 'danger';
    header("Location: index.php");
    exit();
}

// Handle update
if (isset($_POST['update'])) {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $name = trim($_POST['name']);
    $mobileno = trim($_POST['mobileno']);
    $dob = $_POST['date_of_birth'];
    $photo_path = $user['photo'];

    // Check for duplicate username
    if ($username !== $user['username']) {
        $check_stmt = $conn->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
        $check_stmt->bind_param("si", $username, $user_id);
        $check_stmt->execute();
        $check_stmt->store_result();

        if ($check_stmt->num_rows > 0) {
            $message = "Username already taken by another user.";
            $message_type = "danger";
        }
        $check_stmt->close();
    }

    // Only proceed with update if no error so far
    if ($message_type !== 'danger') {
        // Handle photo upload
        if (!empty($_FILES['photo']['name']) && $_FILES['photo']['error'] === 0) {
            $upload_dir = 'uploads/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            $file_name = time() . '_' . basename($_FILES['photo']['name']);
            $target_file = $upload_dir . $file_name;

            if (move_uploaded_file($_FILES['photo']['tmp_name'], $target_file)) {
                $photo_path = $target_file;
            }
        }

        // Update user data
        $stmt = $conn->prepare("UPDATE users SET username=?, email=?, first_name=?, mobileno=?, date_of_birth=?, photo=? WHERE id=?");
        if (!$stmt) {
            die("Prepare failed (update): " . $conn->error);
        }

        $stmt->bind_param("ssssssi", $username, $email, $name, $mobileno, $dob, $photo_path, $user_id);

        if ($stmt->execute()) {
            $message = "Profile updated successfully.";
            $message_type = "success";

            // Refresh user data
            $stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $user = $result->fetch_assoc();
            $stmt->close();
        } else {
            $message = "Update failed: " . $stmt->error;
            $message_type = "danger";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit My Profile</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { padding: 2rem; }
        .profile-photo { width: 150px; height: 150px; object-fit: cover; border-radius: 50%; }
    </style>
</head>
<body>

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

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

    <form method="post" enctype="multipart/form-data">
        <div class="row mb-3">
            <div class="col-md-3">
                <?php if (!empty($user['photo'])): ?>
                    <img src="<?= htmlspecialchars($user['photo']) ?>" class="profile-photo mb-3">
                <?php else: ?>
                    <img src="assets/img/default-profile.png" class="profile-photo mb-3">
                <?php endif; ?>
                <input type="file" name="photo" class="form-control">
            </div>

            <div class="col-md-9">
                <div class="mb-3">
                    <label>Username</label>
                    <input type="text" name="username" class="form-control" value="<?= htmlspecialchars($user['username']) ?>" required>
                </div>

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

                <div class="mb-3">
                    <label>Full Name</label>
                    <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($user['first_name']) ?>">
                </div>

                <div class="mb-3">
                    <label>Mobile Number</label>
                    <input type="text" name="mobileno" class="form-control" value="<?= htmlspecialchars($user['mobileno']) ?>">
                </div>

                <div class="mb-3">
                    <label>Date of Birth</label>
                    <input type="date" name="date_of_birth" class="form-control" value="<?= htmlspecialchars($user['date_of_birth']) ?>">
                </div>

                <div class="d-flex justify-content-end">
                    <button type="submit" name="update" class="btn btn-primary me-2">Save Changes</button>
                    <a href="dashboard_employee.php" class="btn btn-secondary">Cancel</a>
                </div>
            </div>
        </div>
    </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
