<?php
declare(strict_types=1);

require_once __DIR__ . '/../../app/Config/database.php';

class User
{
    private PDO $db;

    public function __construct()
    {
        $this->db = Database::getConnection();
    }

    /**
     * Get all users (descending order)
     */
    public function getAll(): array
    {
        $stmt = $this->db->query("SELECT * FROM users ORDER BY id DESC");
        return $stmt->fetchAll();
    }

    /**
     * Get single user by ID
     */
    public function getById(int $id): ?array
    {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

    /**
     * Add a new user with optional profile image
     */
    public function add(array $data, ?array $file): bool
    {
        $imagePath = null;

        if ($file && $file['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $name = uniqid('user_', true) . '.' . $ext;

            // ✅ Save inside /public/uploads/profile_photos/
            $dest = __DIR__ . '/../../public/uploads/profile_photos/' . $name;
            if (!is_dir(dirname($dest))) {
                mkdir(dirname($dest), 0775, true);
            }
            move_uploaded_file($file['tmp_name'], $dest);

            $imagePath = 'uploads/profile_photos/' . $name;
        }

        $stmt = $this->db->prepare("
            INSERT INTO users (name, email, password_hash, role, status, profile_image)
            VALUES (?, ?, ?, ?, ?, ?)
        ");

        return $stmt->execute([
            $data['name'],
            $data['email'],
            password_hash($data['password'], PASSWORD_DEFAULT),
            $data['role'],
            $data['status'] ?? 'active',
            $imagePath
        ]);
    }

    /**
     * Update existing user with optional new image
     */
    public function update(int $id, array $data, ?array $file): bool
    {
        $imageClause = '';
        $params = [
            $data['name'],
            $data['email'],
            $data['role'],
            $data['status'],
            $id
        ];

        if ($file && $file['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $name = uniqid('user_', true) . '.' . $ext;

            // ✅ Save inside /public/uploads/profile_photos/
            $dest = __DIR__ . '/../../public/uploads/profile_photos/' . $name;
            if (!is_dir(dirname($dest))) {
                mkdir(dirname($dest), 0775, true);
            }
            move_uploaded_file($file['tmp_name'], $dest);

            $imagePath = 'uploads/profile_photos/' . $name;
            $imageClause = ", profile_image = ?";
            array_splice($params, 4, 0, $imagePath);
        }

        $sql = "UPDATE users SET name = ?, email = ?, role = ?, status = ?{$imageClause} WHERE id = ?";
        $stmt = $this->db->prepare($sql);
        return $stmt->execute($params);
    }

    /**
     * Delete user
     */
    public function delete(int $id): bool
    {
        $stmt = $this->db->prepare("DELETE FROM users WHERE id = ?");
        return $stmt->execute([$id]);
    }
}
