<?php
declare(strict_types=1);

require_once __DIR__ . '/../app/init.php';
app_require_login();

$requestedCompanyId = (int) ($_GET['company_id'] ?? 0);
$companyId = app_effective_company_id($requestedCompanyId > 0 ? $requestedCompanyId : null, true);
if ($companyId !== null && $companyId > 0) {
    app_set_context_company_id($companyId);
}
$company = $companyId ? app_company_by_id((int) $companyId) : null;
$counts = app_module_counts($companyId);
$visibleBySlug = [];
foreach (app_visible_modules() as $module) {
    $slug = (string) ($module['slug'] ?? '');
    if ($slug !== '') {
        $visibleBySlug[$slug] = $module;
    }
}

$isArabic = app_ui_language() === 'ar';
$txt = static fn (string $en, string $ar): string => $isArabic ? $ar : $en;
$companyQuery = $companyId ? ('company_id=' . urlencode((string) $companyId)) : '';
$moduleCard = static function (string $slug, string $accent) use ($visibleBySlug, $counts, $companyQuery): ?array {
    $module = $visibleBySlug[$slug] ?? null;
    if (!is_array($module)) {
        return null;
    }
    return [
        'title' => (string) ($module['title'] ?? $slug),
        'subtitle' => (string) ($module['description'] ?? ''),
        'href' => 'module.php?module=' . urlencode($slug) . ($companyQuery !== '' ? '&' . $companyQuery : ''),
        'icon' => (string) ($module['icon'] ?? strtoupper(substr($slug, 0, 2))),
        'count' => (int) ($counts[$slug] ?? 0),
        'accent' => $accent,
    ];
};

$todaySales = 0.0;
$todayRefunds = 0.0;
$todayNet = 0.0;
$expectedOpenCash = 0.0;
$openSessionsCount = 0;
if ($companyId !== null && $companyId > 0) {
    try {
        $pdo = app_pdo();
        $stmt = $pdo->prepare(
            "SELECT
                COALESCE(SUM(CASE WHEN grand_total >= 0 THEN grand_total ELSE 0 END), 0) AS sales_total,
                COALESCE(SUM(CASE WHEN grand_total < 0 THEN ABS(grand_total) ELSE 0 END), 0) AS refund_total,
                COALESCE(SUM(grand_total), 0) AS net_total
             FROM pos_orders
             WHERE company_id = :company_id
               AND DATE(order_date) = :order_date
               AND status <> 'cancelled'"
        );
        $stmt->execute(['company_id' => $companyId, 'order_date' => date('Y-m-d')]);
        $totals = $stmt->fetch() ?: [];
        $todaySales = app_number($totals['sales_total'] ?? 0);
        $todayRefunds = app_number($totals['refund_total'] ?? 0);
        $todayNet = app_number($totals['net_total'] ?? 0);

        $stmt = $pdo->prepare(
            "SELECT COUNT(*), COALESCE(SUM(expected_cash_amount), 0)
             FROM pos_sessions
             WHERE company_id = :company_id
               AND status = 'open'"
        );
        $stmt->execute(['company_id' => $companyId]);
        $sessionTotals = $stmt->fetch(PDO::FETCH_NUM) ?: [0, 0];
        $openSessionsCount = (int) ($sessionTotals[0] ?? 0);
        $expectedOpenCash = app_number($sessionTotals[1] ?? 0);
    } catch (Throwable) {
        // Keep the workspace usable during first migration/bootstrap.
    }
}

$primaryLinks = [
    ['title' => $txt('Open POS Terminal', 'فتح شاشة البيع'), 'href' => 'pos.php' . ($companyQuery !== '' ? '?' . $companyQuery : ''), 'icon' => 'POS', 'accent' => '#14b8a6', 'count' => (int) ($counts['pos_orders'] ?? 0)],
];

$groups = [
    [
        'title' => $txt('POS Operations', 'حركات نقاط البيع'),
        'cards' => array_filter([
            $moduleCard('pos_sessions', '#0f766e'),
            $moduleCard('pos_orders', '#2563eb'),
            $moduleCard('pos_cash_movements', '#f59e0b'),
        ]),
    ],
    [
        'title' => $txt('POS Setup and Catalog', 'إعدادات وكاتالوج نقاط البيع'),
        'cards' => array_filter([
            $moduleCard('pos_registers', '#14b8a6'),
            $moduleCard('products', '#7c3aed'),
            $moduleCard('contacts', '#9333ea'),
            $moduleCard('tax_rates', '#be123c'),
            $moduleCard('cash_accounts', '#16a34a'),
            $moduleCard('bank_accounts', '#0284c7'),
            $moduleCard('cost_centers', '#ca8a04'),
            $moduleCard('posting_account_settings', '#475569'),
        ]),
    ],
];
?>
<!doctype html>
<html <?= app_html_attrs() ?>>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= app_escape((string) app_config('app_name')) ?> - <?= app_escape($txt('Point of Sale', 'نقاط البيع')) ?></title>
  <link rel="icon" href="assets/favicon.svg" type="image/svg+xml">
  <link rel="shortcut icon" href="assets/favicon.svg" type="image/svg+xml">
  <link rel="stylesheet" href="assets/styles.css">
</head>
<body>
<div class="app-shell has-sidebar">
  <?= app_sidebar_nav_html('pos_accounts', null, $companyId) ?>
  <div class="workspace-page">
    <section class="workspace-hero workspace-hero--accounting">
      <div>
        <a class="workspace-back" href="home.php<?= $companyId ? '?company_id=' . (int) $companyId : '' ?>"><?= app_escape($txt('Back to Home', 'رجوع للرئيسية')) ?></a>
        <h1><?= app_escape($txt('Point of Sale', 'نقاط البيع')) ?></h1>
        <p><?= app_escape($txt('A dedicated point-of-sale workspace for cashier sessions, product sales, refunds, split payments, cash in/out, and automatic general-ledger posting.', 'مساحة مستقلة لنقاط البيع تشمل جلسات أمين الصندوق، بيع المنتجات، المرتجعات، الدفعات المقسمة، حركات النقدية، والقيود المحاسبية التلقائية.')) ?></p>
      </div>
      <img src="<?= app_escape(app_logo_path_for_header($company)) ?>" alt="Company Logo">
    </section>

    <section class="workspace-kpis">
      <div class="workspace-kpi"><span><?= app_escape($txt('Open Sessions', 'الجلسات المفتوحة')) ?></span><strong><?= app_escape(number_format($openSessionsCount)) ?></strong></div>
      <div class="workspace-kpi"><span><?= app_escape($txt('Today Sales', 'مبيعات اليوم')) ?></span><strong><?= app_escape(app_money_format($todaySales)) ?></strong></div>
      <div class="workspace-kpi"><span><?= app_escape($txt('Today Refunds', 'مرتجعات اليوم')) ?></span><strong><?= app_escape(app_money_format($todayRefunds)) ?></strong></div>
      <div class="workspace-kpi"><span><?= app_escape($txt('Expected Open Cash', 'النقدية المتوقعة المفتوحة')) ?></span><strong><?= app_escape(app_money_format($expectedOpenCash)) ?></strong></div>
    </section>

    <section class="workspace-section">
      <div class="workspace-section-head">
        <h2><?= app_escape($txt('Cashier Workspace', 'مساحة أمين الصندوق')) ?></h2>
        <span><?= app_escape($txt('Start from the live terminal, then review sessions and posted receipts.', 'ابدأ من شاشة البيع المباشرة ثم راجع الجلسات والإيصالات المرحلة.')) ?></span>
      </div>
      <div class="workspace-card-grid">
        <?php foreach ($primaryLinks as $card): ?>
          <a class="workspace-card" href="<?= app_escape((string) $card['href']) ?>" style="--workspace-accent: <?= app_escape((string) $card['accent']) ?>;">
            <span class="workspace-card-icon"><?= app_escape((string) $card['icon']) ?></span>
            <strong><?= app_escape((string) $card['title']) ?></strong>
            <small><?= app_escape(number_format((int) $card['count'])) ?> <?= app_escape($txt('orders', 'أوامر')) ?></small>
          </a>
        <?php endforeach; ?>
      </div>
    </section>

    <?php foreach ($groups as $group): ?>
      <section class="workspace-section">
        <div class="workspace-section-head">
          <h2><?= app_escape((string) $group['title']) ?></h2>
          <span><?= app_escape(number_format(count((array) $group['cards']))) ?> <?= app_escape($txt('modules', 'وحدات')) ?></span>
        </div>
        <div class="workspace-card-grid">
          <?php foreach ((array) $group['cards'] as $card): ?>
            <a class="workspace-card" href="<?= app_escape((string) $card['href']) ?>" style="--workspace-accent: <?= app_escape((string) $card['accent']) ?>;">
              <span class="workspace-card-icon"><?= app_escape((string) $card['icon']) ?></span>
              <strong><?= app_escape((string) $card['title']) ?></strong>
              <small><?= app_escape(number_format((int) $card['count'])) ?> <?= app_escape($txt('records', 'سجلات')) ?></small>
            </a>
          <?php endforeach; ?>
        </div>
      </section>
    <?php endforeach; ?>
  </div>
</div>
<script src="assets/app.js"></script>
</body>
</html>
