<?php
/**
 * User Controller — CRUD + Permission Management
 */

class UserController {
    private PDO $db;
    private object $user;

    public function __construct(PDO $db, object $user) {
        $this->db = $db;
        $this->user = $user;
    }

    /** GET /users */
    public function index(): void {
        $stmt = $this->db->query("
            SELECT id, username, full_name, department, role, status, created_at, hide_reversals 
            FROM users ORDER BY id ASC
        ");
        $users = $stmt->fetchAll();

        // Attach permissions
        foreach ($users as &$u) {
            $pStmt = $this->db->prepare("SELECT module, can_view, can_create, can_edit, can_delete, can_print FROM permissions WHERE user_id = ?");
            $pStmt->execute([$u['id']]);
            $u['permissions'] = [];
            foreach ($pStmt->fetchAll() as $p) {
                $u['permissions'][$p['module']] = [
                    'view' => (bool)$p['can_view'], 'create' => (bool)$p['can_create'],
                    'edit' => (bool)$p['can_edit'], 'delete' => (bool)$p['can_delete'],
                    'print' => (bool)$p['can_print']
                ];
            }
        }

        Response::success($users);
    }

    /** GET /users/me — Current logged-in user info */
    public function me(): void {
        $stmt = $this->db->prepare("SELECT id, username, full_name, department, role, status, hide_reversals FROM users WHERE id = ?");
        $stmt->execute([$this->user->id]);
        $user = $stmt->fetch();

        $pStmt = $this->db->prepare("SELECT module, can_view, can_create, can_edit, can_delete, can_print FROM permissions WHERE user_id = ?");
        $pStmt->execute([$user['id']]);
        $user['permissions'] = [];
        foreach ($pStmt->fetchAll() as $p) {
            $user['permissions'][$p['module']] = [
                'view' => (bool)$p['can_view'], 'create' => (bool)$p['can_create'],
                'edit' => (bool)$p['can_edit'], 'delete' => (bool)$p['can_delete'],
                'print' => (bool)$p['can_print']
            ];
        }

        Response::success($user);
    }

    /** POST /users */
    public function store(array $data): void {
        Validator::check($data, [
            'username'   => 'required|string|min:3|max:50',
            'full_name'  => 'required|string|max:200',
            'password'   => 'required|string|min:4',
            'department' => 'nullable|string',
            'role'       => 'required|in:admin,manager,operator'
        ]);

        // Check uniqueness
        $stmtCheck = $this->db->prepare("SELECT id FROM users WHERE username = ?");
        $stmtCheck->execute([$data['username']]);
        if ($stmtCheck->fetch()) {
            Response::conflict("یوزر نیم '{$data['username']}' پہلے سے موجود ہے۔");
        }

        $this->db->beginTransaction();
        try {
            $stmt = $this->db->prepare("
                INSERT INTO users (username, full_name, password_hash, department, role, hide_reversals) 
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $data['username'],
                $data['full_name'],
                password_hash($data['password'], PASSWORD_DEFAULT),
                $data['department'] ?? null,
                $data['role'],
                isset($data['hide_reversals']) ? (int)$data['hide_reversals'] : 1
            ]);
            $userId = (int)$this->db->lastInsertId();

            // Save permissions
            if (isset($data['permissions']) && is_array($data['permissions'])) {
                $this->savePermissions($userId, $data['permissions']);
            }

            AuditLogger::log($this->db, $this->user->id, 'CREATED_USER', 'users', $userId, null, $data);
            $this->db->commit();

            Response::created(['id' => $userId], 'صارف کامیابی سے بنایا گیا۔');
        } catch (Exception $e) {
            $this->db->rollBack();
            throw $e;
        }
    }

    /** PUT /users/{id} */
    public function update(int $id, array $data): void {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$id]);
        $existing = $stmt->fetch();
        if (!$existing) Response::notFound('صارف نہیں ملا۔');

        $this->db->beginTransaction();
        try {
            $fields = [];
            $params = [];

            if (isset($data['full_name'])) { $fields[] = 'full_name = ?'; $params[] = $data['full_name']; }
            if (isset($data['department'])) { $fields[] = 'department = ?'; $params[] = $data['department']; }
            if (isset($data['role'])) { $fields[] = 'role = ?'; $params[] = $data['role']; }
            if (isset($data['status'])) { $fields[] = 'status = ?'; $params[] = $data['status']; }
            if (isset($data['hide_reversals'])) { $fields[] = 'hide_reversals = ?'; $params[] = (int)$data['hide_reversals']; }
            if (!empty($data['password'])) {
                $fields[] = 'password_hash = ?';
                $params[] = password_hash($data['password'], PASSWORD_DEFAULT);
            }

            if (!empty($fields)) {
                $params[] = $id;
                $sql = "UPDATE users SET " . implode(', ', $fields) . " WHERE id = ?";
                $this->db->prepare($sql)->execute($params);
            }

            if (isset($data['permissions']) && is_array($data['permissions'])) {
                $this->db->prepare("DELETE FROM permissions WHERE user_id = ?")->execute([$id]);
                $this->savePermissions($id, $data['permissions']);
            }

            AuditLogger::log($this->db, $this->user->id, 'UPDATED_USER', 'users', $id, $existing, $data);
            $this->db->commit();

            Response::success(null, 'صارف اپڈیٹ ہو گیا۔');
        } catch (Exception $e) {
            $this->db->rollBack();
            throw $e;
        }
    }

    /** DELETE /users/{id} */
    public function destroy(int $id): void {
        // Prevent deleting self
        if ($id === $this->user->id) {
            Response::error('آپ اپنا اکاؤنٹ حذف نہیں کر سکتے۔', 403);
        }

        $stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$id]);
        $existing = $stmt->fetch();

        if (!$existing) Response::notFound('صارف نہیں ملا۔');
        if ($existing['role'] === 'admin') Response::error('ایڈمن کو حذف نہیں کیا جا سکتا۔', 403);

        // Soft delete: set status = inactive
        $this->db->prepare("UPDATE users SET status = 'inactive' WHERE id = ?")->execute([$id]);

        AuditLogger::log($this->db, $this->user->id, 'DEACTIVATE_USER', 'users', $id, $existing, ['status' => 'inactive']);

        Response::success(null, 'صارف کو کامیابی سے غیر فعال کر دیا گیا۔');
    }

    private function savePermissions(int $userId, array $permissions): void {
        $stmt = $this->db->prepare("
            INSERT INTO permissions (user_id, module, can_view, can_create, can_edit, can_delete, can_print)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");

        foreach ($permissions as $module => $perms) {
            $stmt->execute([
                $userId,
                $module,
                (int)($perms['view'] ?? 0),
                (int)($perms['create'] ?? 0),
                (int)($perms['edit'] ?? 0),
                (int)($perms['delete'] ?? 0),
                (int)($perms['print'] ?? 0)
            ]);
        }
    }
}
