<?php
declare(strict_types=1);

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

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

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

$title       = trim((string)($_POST['title'] ?? ''));
$category    = trim((string)($_POST['category'] ?? ''));
$amount      = (float)($_POST['amount'] ?? 0);
$expenseDate = trim((string)($_POST['expense_date'] ?? ''));
$notes       = trim((string)($_POST['notes'] ?? ''));

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

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

$attachmentPath = null;

if (!empty($_FILES['attachment']['name']) && is_uploaded_file($_FILES['attachment']['tmp_name'])) {
    $allowedExt = ['pdf', 'jpg', 'jpeg', 'png', 'webp'];
    $maxSize = 5 * 1024 * 1024;

    $fileName = (string)$_FILES['attachment']['name'];
    $fileSize = (int)$_FILES['attachment']['size'];
    $tmpName  = (string)$_FILES['attachment']['tmp_name'];
    $ext      = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowedExt, true)) {
        header('Location: ' . financial_u('expenses.php?err=' . urlencode('نوع الملف غير مسموح')));
        exit;
    }

    if ($fileSize > $maxSize) {
        header('Location: ' . financial_u('expenses.php?err=' . urlencode('حجم الملف أكبر من 5MB')));
        exit;
    }

    $uploadDir = __DIR__ . '/uploads/financial/';

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $newName = 'expense_' . date('YmdHis') . '_' . bin2hex(random_bytes(5)) . '.' . $ext;

    if (!move_uploaded_file($tmpName, $uploadDir . $newName)) {
        header('Location: ' . financial_u('expenses.php?err=' . urlencode('فشل رفع الملف')));
        exit;
    }

    $attachmentPath = 'uploads/financial/' . $newName;
}

try {
    $hasAttachmentPath = financial_has_column($pdo, 'financial_expenses', 'attachment_path');
    $hasCreatedBy      = financial_has_column($pdo, 'financial_expenses', 'created_by');
    $hasVatAmount      = financial_has_column($pdo, 'financial_expenses', 'vat_amount');
    $hasNetAmount      = financial_has_column($pdo, 'financial_expenses', 'net_amount');
    $hasVatRecoverable = financial_has_column($pdo, 'financial_expenses', 'is_vat_recoverable');

    $fields = ['branch_id', 'title', 'category', 'amount', 'expense_date', 'notes'];
    $values = ['?', '?', '?', '?', '?', '?'];
    $params = [
        $branchId,
        $title,
        $category,
        $amount,
        $expenseDate,
        $notes !== '' ? $notes : null
    ];

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

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

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

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

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

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

    $sql = 'INSERT INTO financial_expenses (' . implode(', ', $fields) . ')
            VALUES (' . implode(', ', $values) . ')';

    $st = $pdo->prepare($sql);
    $st->execute($params);

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

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

} catch (Throwable $e) {
    header('Location: ' . financial_u('expenses.php?err=' . urlencode('تعذر حفظ المصروف')));
    exit;
}