<?php
require_once 'db.php';

header('Content-Type: application/json');

function sanitize_input($data) {
    return htmlspecialchars(strip_tags(trim($data)));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (!isset($_POST['user-id']) || !isset($_POST['email']) || !isset($_POST['username'])) {
            throw new Exception('Missing required fields');
        }

        $userId = filter_var($_POST['user-id'], FILTER_VALIDATE_INT);
        $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
        $username = sanitize_input($_POST['username']);
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        $note = isset($_POST['note']) ? sanitize_input($_POST['note']) : '';
        
        $role = isset($_POST['role']) ? sanitize_input($_POST['role']) : '';
        $roleinimators = isset($_POST['roleinimators']) ? sanitize_input($_POST['roleinimators']) : '';
        $isVerified = isset($_POST['is_verified']) ? 1 : 0;
        $permissions = isset($_POST['permissions']) ? $_POST['permissions'] : '[]';

        if (!$userId || !$email) {
            throw new Exception('Invalid input data');
        }

        $db = getDB1Connection();

        $checkUser = $db->prepare("SELECT id FROM utilisateurs WHERE id = ?");
        $checkUser->execute([$userId]);
        if (!$checkUser->fetch()) {
            throw new Exception('User not found');
        }

        $updateFields = [
            'email = ?', 
            'username = ?', 
            'note = ?',
            'role = ?',
            'roleinimators = ?',
            'is_verified = ?',
            'permissions = ?'
        ];
        $params = [$email, $username, $note, $role, $roleinimators, $isVerified, $permissions];

        if (!empty($password)) {
            if (strlen($password) < 8) {
                throw new Exception('Password must be at least 8 characters long');
            }
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $updateFields[] = 'password = ?';
            $params[] = $hashedPassword;
        }

        if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = 'uploads/profile_pictures/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $fileInfo = pathinfo($_FILES['profile_picture']['name']);
            $extension = strtolower($fileInfo['extension']);
            $allowedExtensions = ['jpg', 'jpeg', 'png'];

            if (in_array($extension, $allowedExtensions)) {
                $newFileName = uniqid() . '.' . $extension;
                $uploadFile = $uploadDir . $newFileName;

                if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $uploadFile)) {
                    $updateFields[] = 'profile_picture = ?';
                    $params[] = $uploadFile;
                }
            }
        }

        $params[] = $userId;

        $sql = "UPDATE utilisateurs SET " . implode(', ', $updateFields) . " WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute($params);

        if ($role === "admin" || $roleinimators !== "") {
            $staffDir = 'staff_directories/' . $userId;
            if (!is_dir($staffDir)) {
                mkdir($staffDir, 0777, true);
            }

            $updateStaffDir = $db->prepare("UPDATE utilisateurs SET staff_directory = ? WHERE id = ?");
            $updateStaffDir->execute([$staffDir, $userId]);
        }

        error_log("User update - ID: $userId, Email: $email, Role: $role, Verified: $isVerified");

        if($stmt->rowCount() > 0) {
            echo json_encode([
                'success' => true,
                'message' => 'User updated successfully',
                'data' => [
                    'id' => $userId,
                    'email' => $email,
                    'username' => $username,
                    'note' => $note,
                    'role' => $role,
                    'roleinimators' => $roleinimators,
                    'is_verified' => $isVerified
                ]
            ]);
        } else {
            echo json_encode([
                'success' => true,
                'message' => 'No changes were necessary',
                'data' => [
                    'id' => $userId,
                    'email' => $email,
                    'username' => $username,
                    'note' => $note,
                    'role' => $role,
                    'roleinimators' => $roleinimators,
                    'is_verified' => $isVerified
                ]
            ]);
        }

    } catch(PDOException $e) {
        error_log("Database error: " . $e->getMessage());
        echo json_encode([
            'success' => false,
            'message' => 'Database error occurred',
            'debug' => $e->getMessage() 
        ]);
    } catch(Exception $e) {
        error_log("General error: " . $e->getMessage());
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage()
        ]);
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method'
    ]);
}