<?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,
    ];
};

$groups = [
    [
        'title' => $txt('Daily Operations', 'الحركة اليومية'),
        'cards' => array_filter([
            $moduleCard('journal_entries', '#0f766e'),
            $moduleCard('sales_invoices', '#2563eb'),
            $moduleCard('purchase_bills', '#ea580c'),
            $moduleCard('expenses', '#dc2626'),
            $moduleCard('sales_returns', '#0e7490'),
            $moduleCard('purchase_returns', '#b45309'),
            $moduleCard('expense_returns', '#be123c'),
            $moduleCard('prepaid_expenses', '#7c3aed'),
            $moduleCard('payments', '#0891b2'),
        ]),
    ],
    [
        'title' => $txt('Assets and Automation', 'الأصول والقيود الآلية'),
        'cards' => array_filter([
            $moduleCard('assets', '#475569'),
            $moduleCard('depreciation_runs', '#ef4444'),
            $moduleCard('prepaid_amortization_runs', '#8b5cf6'),
            $moduleCard('inventory_movements', '#f59e0b'),
        ]),
    ],
    [
        'title' => $txt('Setup', 'الإعدادات'),
        'cards' => array_filter([
            $moduleCard('chart_of_accounts', '#1d4ed8'),
            $moduleCard('posting_account_settings', '#0f766e'),
            $moduleCard('contacts', '#9333ea'),
            $moduleCard('tax_rates', '#be123c'),
            $moduleCard('bank_accounts', '#0284c7'),
            $moduleCard('cash_accounts', '#16a34a'),
            $moduleCard('cost_centers', '#ca8a04'),
            $moduleCard('budgets', '#64748b'),
        ]),
    ],
];

$reportLinks = [
    ['title' => $txt('Dashboard', 'لوحة المؤشرات'), 'href' => 'index.php' . ($companyQuery !== '' ? '?' . $companyQuery : ''), 'icon' => 'DB', 'accent' => '#f59e0b'],
    ['title' => $txt('Report Designer', 'مصمم التقارير'), 'href' => 'reports.php' . ($companyQuery !== '' ? '?' . $companyQuery : ''), 'icon' => 'RP', 'accent' => '#7c3aed'],
    ['title' => $txt('Account Statement', 'كشف حساب'), 'href' => 'accounting_reports.php?report=ledger' . ($companyQuery !== '' ? '&' . $companyQuery : ''), 'icon' => 'LG', 'accent' => '#2563eb'],
    ['title' => $txt('Trial Balance', 'ميزان المراجعة'), 'href' => 'accounting_reports.php?report=trial_balance' . ($companyQuery !== '' ? '&' . $companyQuery : ''), 'icon' => 'TB', 'accent' => '#0f766e'],
    ['title' => $txt('Financial Statements', 'القوائم المالية'), 'href' => 'accounting_reports.php?report=income_statement' . ($companyQuery !== '' ? '&' . $companyQuery : ''), 'icon' => 'FS', 'accent' => '#dc2626'],
];
?>
<!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('General Accounting', 'الحسابات العامة')) ?></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('accounting', 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('General Accounting', 'الحسابات العامة')) ?></h1>
        <p><?= app_escape($txt('All accounting modules, financial reports, and setup screens are grouped here away from HR.', 'كل وحدات الحسابات والتقارير المالية والإعدادات المحاسبية مجمعة هنا بعيدًا عن الموارد البشرية.')) ?></p>
      </div>
      <img src="<?= app_escape(app_logo_path_for_header($company)) ?>" alt="Company Logo">
    </section>

    <section class="workspace-section">
      <div class="workspace-section-head">
        <h2><?= app_escape($txt('Accounting Reports', 'التقارير المحاسبية')) ?></h2>
        <span><?= app_escape($txt('Dashboards, statements, trial balance, and financial statements.', 'لوحات مؤشرات وكشوف حساب وميزان مراجعة وقوائم مالية.')) ?></span>
      </div>
      <div class="workspace-card-grid">
        <?php foreach ($reportLinks 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($txt('Open', 'فتح')) ?></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>
