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

$operationCards = array_filter([
    $moduleCard('excellence_operations', '#0f766e'),
    $moduleCard('excellence_hospital_expenses', '#dc2626'),
    $moduleCard('excellence_admin_expenses', '#f59e0b'),
    $moduleCard('excellence_salaries', '#2563eb'),
]);
$setupCards = array_filter([
    $moduleCard('excellence_hospitals', '#0891b2'),
    $moduleCard('excellence_devices', '#7c3aed'),
]);
$totalRevenue = 0.0;
$totalHospitalCosts = 0.0;
$totalAdmin = 0.0;
$totalSalaries = 0.0;
if ($companyId !== null && $companyId > 0) {
    try {
        $pdo = app_pdo();
        $stmt = $pdo->prepare("SELECT COALESCE(SUM(revenue_amount),0), COALESCE(SUM(hospital_expense_amount),0) FROM excellence_operations WHERE company_id = :company_id AND status <> 'cancelled'");
        $stmt->execute(['company_id' => $companyId]);
        $totals = $stmt->fetch(PDO::FETCH_NUM) ?: [0, 0];
        $totalRevenue = app_number($totals[0] ?? 0);
        $totalHospitalCosts = app_number($totals[1] ?? 0);
        $stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM excellence_admin_expenses WHERE company_id = :company_id AND status = 'posted'");
        $stmt->execute(['company_id' => $companyId]);
        $totalAdmin = app_number($stmt->fetchColumn() ?: 0);
        $stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM excellence_salaries WHERE company_id = :company_id AND status = 'posted'");
        $stmt->execute(['company_id' => $companyId]);
        $totalSalaries = app_number($stmt->fetchColumn() ?: 0);
    } catch (Throwable) {
        // The workspace should still render during first migration/bootstrap.
    }
}
$grossNet = $totalRevenue - $totalHospitalCosts;
$netAfterOverheads = $grossNet - $totalAdmin - $totalSalaries;
?>
<!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('EXcellence Accounts', 'حسابات EXcellence')) ?></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('excellence_accounts', null, $companyId) ?>
  <div class="workspace-page">
    <section class="workspace-hero workspace-hero--accounting">
      <div>
        <a class="workspace-back" href="portal.php<?= $companyId ? '?company_id=' . (int) $companyId : '' ?>"><?= app_escape($txt('Back to Portal', 'رجوع لبوابة الوحدات')) ?></a>
        <h1><?= app_escape($txt('EXcellence Accounts', 'حسابات EXcellence')) ?></h1>
        <p><?= app_escape($txt('A dedicated workspace for medical device rental operations with hospitals, patient procedures, hospital cost settlements, administrative expenses, salaries, and automatic GL 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('Operation Revenue', 'إيراد العمليات')) ?></span><strong><?= app_escape(app_money_format($totalRevenue)) ?></strong></div>
      <div class="workspace-kpi"><span><?= app_escape($txt('Hospital Costs', 'تكاليف المستشفيات')) ?></span><strong><?= app_escape(app_money_format($totalHospitalCosts)) ?></strong></div>
      <div class="workspace-kpi"><span><?= app_escape($txt('Gross Operation Margin', 'مجمل ربح العمليات')) ?></span><strong><?= app_escape(app_money_format($grossNet)) ?></strong></div>
      <div class="workspace-kpi"><span><?= app_escape($txt('Net After Overheads', 'الصافي بعد المصروفات')) ?></span><strong><?= app_escape(app_money_format($netAfterOverheads)) ?></strong></div>
    </section>

    <section class="workspace-section">
      <div class="workspace-section-head">
        <h2><?= app_escape($txt('Operations', 'الحركات')) ?></h2>
        <span><?= app_escape($txt('Hospital procedure rentals, hospital payments, admin expenses, and salaries.', 'عمليات التأجير للمستشفيات، مدفوعات المستشفيات، المصروفات الإدارية، والرواتب.')) ?></span>
      </div>
      <div class="workspace-card-grid">
        <?php foreach ($operationCards 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>

    <section class="workspace-section">
      <div class="workspace-section-head">
        <h2><?= app_escape($txt('Setup', 'الإعدادات')) ?></h2>
        <span><?= app_escape($txt('Hospitals and medical devices used by operations.', 'تعريف المستشفيات والأجهزة الطبية المستخدمة في العمليات.')) ?></span>
      </div>
      <div class="workspace-card-grid">
        <?php foreach ($setupCards 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>
  </div>
</div>
<script src="assets/app.js"></script>
</body>
</html>
