<?php
// hr_api/profile.php

// Include the reusable CORS handler
require_once __DIR__ . '/cors.php';


session_start();
require_once __DIR__ . '/db.php';

// Check if user is logged in
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role'])) {
    http_response_code(401); // Unauthorized
    echo json_encode(['success' => false, 'message' => 'Unauthorized: Please log in.']);
    exit();
}

$user_id = $_SESSION['user_id'];
$current_user_role = $_SESSION['user_role'];

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        try {
            $stmt = $pdo->prepare("SELECT id, name, username, email, role, status, profile_image, region, department FROM users WHERE id = :id LIMIT 1");
            $stmt->execute(['id' => $user_id]);
            $user_data = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user_data) {
                unset($user_data['password']);
                echo json_encode(['success' => true, 'user' => $user_data]);
            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'User profile not found.']);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
        }
        break;

    case 'PUT':
        $input = json_decode(file_get_contents('php://input'), true);

        $name = $input['name'] ?? null;
        $username = $input['username'] ?? null;
        $email = $input['email'] ?? null;
        $password = $input['password'] ?? null;

        // --- NEW LOGIC: FETCH CURRENT USER DATA FOR COMPARISON ---
        try {
            $stmt_current = $pdo->prepare("SELECT username, email FROM users WHERE id = :id LIMIT 1");
            $stmt_current->execute(['id' => $user_id]);
            $current_user_data = $stmt_current->fetch(PDO::FETCH_ASSOC);

            // If the user's role is regional_hr or hod, prevent username or email changes
            if (($current_user_role === 'regional_hr' || $current_user_role === 'hod') && $current_user_data) {
                if ($username !== $current_user_data['username'] || $email !== $current_user_data['email']) {
                    http_response_code(403);
                    echo json_encode(['success' => false, 'message' => 'You do not have permission to change your username or email.']);
                    exit();
                }
            }
        } catch (PDOException $e) {
            // Handle database error during the pre-check
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Database error during permission check: ' . $e->getMessage()]);
            exit();
        }

        if (empty($name) || empty($username) || empty($email)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Name, username, and email are required for update.']);
            exit();
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid email format.']);
            exit();
        }
        if ($password && strlen($password) < 6) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'New password must be at least 6 characters.']);
            exit();
        }

        try {
            // Check for duplicate username/email (excluding current user's own)
            $stmt_check_dupes = $pdo->prepare("SELECT id FROM users WHERE (username = :username OR email = :email) AND id != :id");
            $stmt_check_dupes->execute(['username' => $username, 'email' => $email, 'id' => $user_id]);
            if ($stmt_check_dupes->rowCount() > 0) {
                http_response_code(409);
                echo json_encode(['success' => false, 'message' => 'Username or email already exists for another user.']);
                exit();
            }

            $sql = "UPDATE users SET name = :name, username = :username, email = :email";
            $params = [
                'name' => $name,
                'username' => $username,
                'email' => $email,
                'id' => $user_id
            ];

            if ($password) {
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $sql .= ", password = :password";
                $params['password'] = $hashed_password;
            }

            $sql .= " WHERE id = :id";

            $stmt = $pdo->prepare($sql);
            if ($stmt->execute($params)) {
                echo json_encode(['success' => true, 'message' => 'Profile updated successfully.']);
            } else {
                http_response_code(500);
                echo json_encode(['success' => false, 'message' => 'Failed to update profile: ' . $stmt->errorInfo()[2]]);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Database error updating profile: ' . $e->getMessage()]);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed.']);
        break;
}
?>