<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('companies.manage');

require_once __DIR__ . '/../config/database.php';

function esc($v){ return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8'); }

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) die("Missing company id.");

$cStmt = $pdo->prepare("SELECT * FROM companies WHERE id=?");
$cStmt->execute([$id]);
$company = $cStmt->fetch(PDO::FETCH_ASSOC);
if (!$company) die("Company not found.");

// Meter summary (linked by current_holder_company_id)
$sum = $pdo->prepare("
    SELECT status, COUNT(*) AS cnt
    FROM meters
    WHERE current_holder_company_id = ?
    GROUP BY status
");
$sum->execute([$id]);
$summaryRows = $sum->fetchAll(PDO::FETCH_ASSOC);

$summary = [
    'IN_STOCK' => 0,
    'WITH_DISTRIBUTOR' => 0,
    'INSTALLED' => 0,
    'FAULTY' => 0
];
foreach ($summaryRows as $r) {
    $summary[$r['status']] = (int)$r['cnt'];
}
$totalMeters = array_sum($summary);

// Latest meters
$mStmt = $pdo->prepare("
    SELECT id, meter_number, meter_type, status, created_at
    FROM meters
    WHERE current_holder_company_id = ?
    ORDER BY created_at DESC
    LIMIT 20
");
$mStmt->execute([$id]);
$meters = $mStmt->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>

<div class="main-content">

    <div class="page-header">
        <h2><?= esc($company['company_name']) ?></h2>
        <p class="page-subtitle">Company profile and linked operational summary.</p>
    </div>

    <div class="breadcrumbs" style="font-size:13px;color:#6b7280;margin-bottom:14px;">
        Dashboard › Companies › <span style="color:var(--edm-orange);font-weight:600;">View</span>
    </div>

    <div class="dashboard-grid" style="grid-template-columns:repeat(auto-fit,minmax(220px,1fr));margin-bottom:18px;">
        <div class="stat-card orange">
            <h4>Total Linked Meters</h4>
            <div class="number"><?= (int)$totalMeters ?></div>
        </div>
        <div class="stat-card green">
            <h4>Installed</h4>
            <div class="number"><?= (int)$summary['INSTALLED'] ?></div>
        </div>
        <div class="stat-card blue">
            <h4>With Distributor</h4>
            <div class="number"><?= (int)$summary['WITH_DISTRIBUTOR'] ?></div>
        </div>
        <div class="stat-card red">
            <h4>Faulty</h4>
            <div class="number"><?= (int)$summary['FAULTY'] ?></div>
        </div>
    </div>

    <div class="table-wrap" style="padding:18px;margin-bottom:18px;">
        <div style="display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;">
            <div>
                <div style="font-weight:700;color:#111827;"><?= esc($company['company_type']) ?> • <?= esc($company['status'] ?? 'ACTIVE') ?></div>
                <div style="color:#6b7280;font-size:13px;margin-top:6px;">
                    Contact: <?= esc($company['contact_person']) ?> • <?= esc($company['email']) ?> • <?= esc($company['phone']) ?><br>
                    Location: <?= esc($company['city']) ?>, <?= esc($company['province']) ?>
                </div>
            </div>

            <div style="display:flex;gap:10px;align-items:flex-start;">
                <a class="action-btn" href="companies.php" style="text-decoration:none;">Back</a>
                <a class="action-btn black" href="edit_company.php?id=<?= (int)$company['id'] ?>" style="text-decoration:none;">Edit</a>
            </div>
        </div>
    </div>

    <div class="table-wrap">
        <div style="padding:14px 16px;border-bottom:1px solid #e5e7eb;font-weight:700;">
            Latest Linked Meters (20)
        </div>

        <div style="overflow-x:auto;-webkit-overflow-scrolling:touch;">
            <table>
                <thead>
                    <tr>
                        <th>Meter Number</th>
                        <th>Type</th>
                        <th>Status</th>
                        <th>Created</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$meters): ?>
                    <tr><td colspan="4" style="padding:16px;color:#6b7280;">No meters linked to this company.</td></tr>
                <?php else: ?>
                    <?php foreach ($meters as $m): ?>
                        <tr>
                            <td><?= esc($m['meter_number']) ?></td>
                            <td><?= esc($m['meter_type']) ?></td>
                            <td><span class="status <?= esc($m['status']) ?>"><?= esc($m['status']) ?></span></td>
                            <td><?= esc($m['created_at']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>