<?php
/**
 * Bulk Approve Invoices
 * POST /v1/invoices/bulk-approve
 * Approves multiple invoices at once
 */

use App\Core\Database;
use App\Core\AuditLogger;
use App\Middleware\RoleMiddleware;

$decoded = RoleMiddleware::require(['super_admin', 'admin', 'accountant']);
$data = input();

$ids = $data['ids'] ?? [];
if (empty($ids) || !is_array($ids)) {
    json_error('يرجى اختيار فاتورة واحدة على الأقل', 422);
}

$db = Database::getInstance();
$tenantId = $decoded['tenant_id'];
$role = $decoded['role'];

$approved = 0;
$errors = [];

foreach ($ids as $id) {
    try {
        // Verify access
        $query = $role === 'super_admin'
            ? "SELECT id, status FROM invoices WHERE id = ? AND status = 'extracted'"
            : "SELECT id, status FROM invoices WHERE id = ? AND tenant_id = ? AND status = 'extracted'";
        $params = $role === 'super_admin' ? [$id] : [$id, $tenantId];

        $stmt = $db->prepare($query);
        $stmt->execute($params);
        $invoice = $stmt->fetch();

        if (!$invoice) {
            $errors[] = "$id: غير موجودة أو معتمدة مسبقاً";
            continue;
        }

        $db->prepare("UPDATE invoices SET status = 'approved', updated_at = NOW() WHERE id = ?")
           ->execute([$id]);

        $approved++;

        AuditLogger::log('invoice.bulk_approved', 'invoice', $id, null, [
            'batch_size' => count($ids),
        ], $decoded);

    } catch (\Exception $e) {
        $errors[] = "$id: " . $e->getMessage();
    }
}

json_success([
    'approved_count' => $approved,
    'total_requested' => count($ids),
    'errors' => $errors,
], "تم اعتماد $approved فاتورة بنجاح");
