<?php
declare(strict_types=1);

require_once __DIR__ . '/_auth.php';
require_once __DIR__ . '/_tax.php';
financial_require_access();

$debug = (isset($_GET['debug']) && $_GET['debug'] === '1');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ' . financial_u('income.php'));
    exit;
}

$pdo      = financial_db();
$branchId = financial_branch_id();
$userId   = financial_user_id();

$clientName    = trim((string)($_POST['client_name'] ?? ''));
$serviceType   = trim((string)($_POST['service_type'] ?? ''));
$amount        = (float)($_POST['amount'] ?? 0);
$paymentMethod = trim((string)($_POST['payment_method'] ?? ''));
$incomeDate    = trim((string)($_POST['income_date'] ?? ''));
$caseId        = (int)($_POST['case_id'] ?? 0);
$notes         = trim((string)($_POST['notes'] ?? ''));

if ($clientName === '' || $serviceType === '' || $amount <= 0 || $paymentMethod === '' || $incomeDate === '') {
    header('Location: ' . financial_u('income.php?err=' . urlencode('يرجى تعبئة جميع الحقول المطلوبة بشكل صحيح')));
    exit;
}

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $incomeDate)) {
    header('Location: ' . financial_u('income.php?err=' . urlencode('تاريخ المدخول غير صحيح')));
    exit;
}

try {
    $hasCaseId         = financial_has_column($pdo, 'financial_income', 'case_id');
    $hasCreatedBy      = financial_has_column($pdo, 'financial_income', 'created_by');
    $hasNotes          = financial_has_column($pdo, 'financial_income', 'notes');
    $hasAttachmentPath = financial_has_column($pdo, 'financial_income', 'attachment_path');
    $hasVatAmount      = financial_has_column($pdo, 'financial_income', 'vat_amount');
    $hasNetAmount      = financial_has_column($pdo, 'financial_income', 'net_amount');
    $hasVatApplicable  = financial_has_column($pdo, 'financial_income', 'is_vat_applicable');

    $attachmentPath = null;
    if ($hasAttachmentPath) {
        $attachmentPath = financial_upload_attachment('attachment', 'income');
    }

    $fields = ['branch_id', 'client_name', 'service_type', 'amount', 'payment_method', 'income_date'];
    $values = ['?', '?', '?', '?', '?', '?'];
    $params = [$branchId, $clientName, $serviceType, $amount, $paymentMethod, $incomeDate];

    [$vatAmount, $netAmount] = financial_tax_from_gross($amount);

    if ($hasVatAmount) {
        $fields[] = 'vat_amount';
        $values[] = '?';
        $params[] = $vatAmount;
    }

    if ($hasNetAmount) {
        $fields[] = 'net_amount';
        $values[] = '?';
        $params[] = $netAmount;
    }

    if ($hasVatApplicable) {
        $fields[] = 'is_vat_applicable';
        $values[] = '?';
        $params[] = 1;
    }

    if ($hasCaseId) {
        $fields[] = 'case_id';
        $values[] = '?';
        $params[] = ($caseId > 0 ? $caseId : null);
    }

    if ($hasNotes) {
        $fields[] = 'notes';
        $values[] = '?';
        $params[] = ($notes !== '' ? $notes : null);
    }

    if ($hasAttachmentPath) {
        $fields[] = 'attachment_path';
        $values[] = '?';
        $params[] = $attachmentPath;
    }

    if ($hasCreatedBy) {
        $fields[] = 'created_by';
        $values[] = '?';
        $params[] = ($userId > 0 ? $userId : null);
    }

    $sql = 'INSERT INTO financial_income (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
    $st = $pdo->prepare($sql);
    $st->execute($params);

    financial_recalculate_tax_summary($pdo, $branchId, (int)substr($incomeDate, 0, 4));

    header('Location: ' . financial_u('income.php?msg=' . urlencode('تم حفظ المدخول بنجاح')));
    exit;

} catch (Throwable $e) {
    if ($debug) {
        http_response_code(500);
        echo '<pre style="direction:ltr;text-align:left;background:#111;color:#fff;padding:14px;border-radius:10px;white-space:pre-wrap">';
        echo "SAVE INCOME ERROR\n";
        echo 'Message: ' . $e->getMessage() . "\n\n";
        echo 'File: ' . $e->getFile() . "\n";
        echo 'Line: ' . $e->getLine() . "\n\n";
        echo "POST:\n";
        print_r($_POST);
        echo "\nFILES:\n";
        print_r($_FILES);
        echo "\nTrace:\n" . $e->getTraceAsString();
        echo '</pre>';
        exit;
    }

    header('Location: ' . financial_u('income.php?err=' . urlencode($e->getMessage() ?: 'تعذر حفظ المدخول')));
    exit;
}
