<?php
/**
 * Reject Invoice
 */

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

$decoded = RoleMiddleware::require(['super_admin', 'admin', 'accountant']);
$db = Database::getInstance();

$data = json_decode(file_get_contents('php://input'), true);
$id = $data['id'] ?? null;

if (!$id) {
    json_error('Invoice ID is required', 422);
}

try {
    $db->beginTransaction();

    $stmt = $db->prepare("SELECT * FROM invoices WHERE id = ? FOR UPDATE");
    $stmt->execute([$id]);
    $invoice = $stmt->fetch();

    if (!$invoice) json_error('Invoice not found', 404);
    if ($invoice['status'] === 'approved') json_error('لا يمكن رفض فاتورة معتمدة', 400);

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

    $db->commit();

    AuditLogger::log('invoice.rejected', 'invoice', $id, [
        'old_status' => $invoice['status'],
    ], [
        'new_status' => 'rejected',
    ], $decoded);

    json_success(null, 'تم رفض الفاتورة بنجاح');

} catch (\Exception $e) {
    if ($db->inTransaction()) $db->rollBack();
    error_log("Invoice Reject Error: " . $e->getMessage());
    json_error('فشل في رفض الفاتورة', 500);
}
