<?php
/**
 * includes/functions.php — עזרים משותפים
 */
declare(strict_types=1);

require_once dirname(__DIR__) . '/config/config.php';
require_once __DIR__ . '/db.php';

/* ============================================================
   פלט ובטיחות
   ============================================================ */

function h(?string $s): string
{
    return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function redirect(string $url): never
{
    header('Location: ' . $url);
    exit;
}

function csrf_token(): string
{
    if (empty($_SESSION['csrf'])) {
        $_SESSION['csrf'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf'];
}

function csrf_field(): string
{
    return '<input type="hidden" name="csrf" value="' . h(csrf_token()) . '">';
}

function csrf_check(): void
{
    $token = $_POST['csrf'] ?? '';
    if (!is_string($token) || empty($_SESSION['csrf']) || !hash_equals($_SESSION['csrf'], $token)) {
        http_response_code(419);
        die('פג תוקף הטופס. רענן את הדף ונסה שוב.');
    }
}

/* ============================================================
   קלט
   ============================================================ */

function post(string $key, $default = ''): string
{
    return isset($_POST[$key]) && is_scalar($_POST[$key]) ? trim((string)$_POST[$key]) : (string)$default;
}

function get(string $key, $default = ''): string
{
    return isset($_GET[$key]) && is_scalar($_GET[$key]) ? trim((string)$_GET[$key]) : (string)$default;
}

function post_int(string $key, int $default = 0): int
{
    return isset($_POST[$key]) ? (int)$_POST[$key] : $default;
}

function get_int(string $key, int $default = 0): int
{
    return isset($_GET[$key]) ? (int)$_GET[$key] : $default;
}

function post_dec(string $key, float $default = 0.0): float
{
    $v = str_replace([',', ' '], '', post($key, (string)$default));
    return is_numeric($v) ? (float)$v : $default;
}

/* ============================================================
   הודעות מערכת (Flash)
   ============================================================ */

function flash(string $type, string $msg): void
{
    $_SESSION['flash'][] = ['type' => $type, 'msg' => $msg];
}

function flash_pull(): array
{
    $f = $_SESSION['flash'] ?? [];
    unset($_SESSION['flash']);
    return $f;
}

/* ============================================================
   הרשאות
   ============================================================ */

function is_logged_in(): bool
{
    return !empty($_SESSION['uid']) && !empty($_SESSION['bid']);
}

function require_login(): void
{
    if (!is_logged_in()) {
        redirect('login.php');
    }
}

function uid(): int
{
    return (int)($_SESSION['uid'] ?? 0);
}

function bid(): int
{
    return (int)($_SESSION['bid'] ?? 0);
}

function current_user(): ?array
{
    static $u = null;
    if ($u === null && uid()) {
        $u = Db::one('SELECT * FROM users WHERE id = ?', [uid()]);
    }
    return $u ?: null;
}

function current_business(): ?array
{
    static $b = null;
    if ($b === null && bid()) {
        $b = Db::one('SELECT * FROM businesses WHERE id = ?', [bid()]);
    }
    return $b ?: null;
}

function vat_rate(): float
{
    $b = current_business();
    return $b ? (float)$b['vat_rate'] : DEFAULT_VAT;
}

/* ============================================================
   תצוגה
   ============================================================ */

function money(float $n, string $currency = 'ILS'): string
{
    $sym = ['ILS' => '₪', 'USD' => '$', 'EUR' => '€'][$currency] ?? '';
    return $sym . number_format($n, 2);
}

function qty_fmt(float $n): string
{
    return rtrim(rtrim(number_format($n, 3), '0'), '.');
}

function date_he(?string $d): string
{
    if (!$d || $d === '0000-00-00') return '—';
    $ts = strtotime($d);
    return $ts ? date('d/m/Y', $ts) : '—';
}

function status_label(string $s): string
{
    return [
        'draft'    => 'טיוטה',
        'sent'     => 'נשלחה',
        'accepted' => 'אושרה',
        'rejected' => 'נדחתה',
        'expired'  => 'פג תוקף',
    ][$s] ?? $s;
}

/* ============================================================
   מנוע חישוב — סכומים ומע"מ
   כל המחירים נשמרים ללא מע"מ; המע"מ מחושב על הסכום לאחר הנחה.
   ============================================================ */

/**
 * @param array $items  [['qty'=>,'unit_price'=>,'discount_pct'=>], ...]
 * @return array{lines:array,subtotal:float,discount_amount:float,taxable:float,vat:float,total:float}
 */
function calc_totals(array $items, float $vatRate, string $discountType = 'none', float $discountValue = 0.0): array
{
    $lines    = [];
    $subtotal = 0.0;

    foreach ($items as $i => $it) {
        $qty   = (float)($it['qty'] ?? 0);
        $price = (float)($it['unit_price'] ?? 0);
        $disc  = max(0.0, min(100.0, (float)($it['discount_pct'] ?? 0)));
        $line  = round($qty * $price * (1 - $disc / 100), 2);
        $lines[$i] = $line;
        $subtotal += $line;
    }
    $subtotal = round($subtotal, 2);

    $discountAmount = 0.0;
    if ($discountType === 'percent') {
        $discountAmount = round($subtotal * max(0.0, min(100.0, $discountValue)) / 100, 2);
    } elseif ($discountType === 'amount') {
        $discountAmount = round(max(0.0, min($subtotal, $discountValue)), 2);
    }

    $taxable = round($subtotal - $discountAmount, 2);
    $vat     = round($taxable * $vatRate / 100, 2);
    $total   = round($taxable + $vat, 2);

    return [
        'lines'           => $lines,
        'subtotal'        => $subtotal,
        'discount_amount' => $discountAmount,
        'taxable'         => $taxable,
        'vat'             => $vat,
        'total'           => $total,
    ];
}

/**
 * מספר הצעה הבא לעסק — בתוך טרנזקציה כדי למנוע כפילויות
 */
function next_quote_number(int $businessId): string
{
    $pdo = Db::conn();
    $own = !$pdo->inTransaction();
    if ($own) $pdo->beginTransaction();

    $row = Db::one('SELECT quote_prefix, quote_counter FROM businesses WHERE id = ? FOR UPDATE', [$businessId]);
    $next = (int)$row['quote_counter'] + 1;
    Db::run('UPDATE businesses SET quote_counter = ? WHERE id = ?', [$next, $businessId]);

    if ($own) $pdo->commit();

    return $row['quote_prefix'] . str_pad((string)$next, 4, '0', STR_PAD_LEFT);
}

function log_quote(int $quoteId, string $action, ?string $details = null): void
{
    Db::run(
        'INSERT INTO quote_log (quote_id, user_id, action, details) VALUES (?,?,?,?)',
        [$quoteId, uid() ?: null, $action, $details]
    );
}

/** סכום במילים — לשורת הסיכום בהצעה */
function num_to_words_he(float $n): string
{
    $shekels = (int)floor($n);
    $agorot  = (int)round(($n - $shekels) * 100);
    $out = _he_group($shekels) . ' ש"ח';
    if ($agorot > 0) {
        $out .= ' ו' . _he_group($agorot) . ' אגורות';
    }
    return $out;
}

function _he_group(int $n): string
{
    if ($n === 0) return 'אפס';
    $ones = ['', 'אחד', 'שניים', 'שלושה', 'ארבעה', 'חמישה', 'שישה', 'שבעה', 'שמונה', 'תשעה'];
    $tens = ['', 'עשרה', 'עשרים', 'שלושים', 'ארבעים', 'חמישים', 'שישים', 'שבעים', 'שמונים', 'תשעים'];
    $huns = ['', 'מאה', 'מאתיים', 'שלוש מאות', 'ארבע מאות', 'חמש מאות', 'שש מאות', 'שבע מאות', 'שמונה מאות', 'תשע מאות'];

    // צורת נסמך לאלפים: שלושת אלפים, ארבעת אלפים ...
    $thc = ['', 'אלף', 'אלפיים', 'שלושת אלפים', 'ארבעת אלפים', 'חמשת אלפים',
            'ששת אלפים', 'שבעת אלפים', 'שמונת אלפים', 'תשעת אלפים'];

    $parts = [];
    if ($n >= 1000) {
        $th = intdiv($n, 1000);
        $parts[] = $th <= 9 ? $thc[$th] : _he_group($th) . ' אלף';
        $n %= 1000;
    }
    if ($n >= 100) { $parts[] = $huns[intdiv($n, 100)]; $n %= 100; }
    if ($n >= 20)  { $parts[] = $tens[intdiv($n, 10)];  $n %= 10; }
    elseif ($n >= 11) { $parts[] = $ones[$n - 10] . ' עשר'; $n = 0; }
    elseif ($n === 10) { $parts[] = 'עשרה'; $n = 0; }
    if ($n > 0) $parts[] = $ones[$n];

    return implode(' ו', array_filter($parts)) ?: 'אפס';
}
