<?php
session_start();
require_once __DIR__ . '/../config/database.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

/*
|--------------------------------------------------------------------------
| FILTERS
|--------------------------------------------------------------------------
*/
$typeFilter = $_GET['type'] ?? '';
$searchMeter = $_GET['meter'] ?? '';
$page = max((int)($_GET['page'] ?? 1), 1);
$limit = 20;
$offset = ($page - 1) * $limit;

/*
|--------------------------------------------------------------------------
| EXPORT CSV
|--------------------------------------------------------------------------
*/
if (isset($_GET['export']) && $_GET['export'] === '1') {

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="activity_export.csv"');

    $output = fopen('php://output', 'w');
    fputcsv($output, ['Type','Meter','Title','Description','User','Date']);

    $queryExport = "
    (
        SELECT 
            'MOVEMENT' AS type,
            m.meter_number,
            mm.movement_type AS title,
            mm.reason AS description,
            u.email AS user_email,
            mm.created_at
        FROM meter_movements mm
        JOIN meters m ON mm.meter_id = m.id
        LEFT JOIN users u ON mm.moved_by_user_id = u.id
    )
    UNION ALL
    (
        SELECT
            'AUDIT' AS type,
            NULL,
            al.action,
            NULL,
            u.email,
            al.created_at
        FROM audit_logs al
        LEFT JOIN users u ON al.user_id = u.id
    )
    ORDER BY created_at DESC
    ";

    foreach ($pdo->query($queryExport) as $row) {
        fputcsv($output, $row);
    }

    fclose($output);
    exit;
}

/*
|--------------------------------------------------------------------------
| BUILD WHERE CONDITIONS
|--------------------------------------------------------------------------
*/
$whereMovement = "WHERE 1=1";
$whereAudit = "WHERE 1=1";
$params = [];

if ($searchMeter) {
    $whereMovement .= " AND m.meter_number LIKE ?";
    $params[] = "%$searchMeter%";
}

if ($typeFilter === 'MOVEMENT') {
    $whereAudit .= " AND 1=0";
}

if ($typeFilter === 'AUDIT') {
    $whereMovement .= " AND 1=0";
}

/*
|--------------------------------------------------------------------------
| FETCH TIMELINE
|--------------------------------------------------------------------------
*/
$query = "
(
    SELECT 
        'MOVEMENT' AS type,
        m.meter_number,
        mm.movement_type AS title,
        mm.reason AS description,
        u.email AS user_email,
        mm.created_at
    FROM meter_movements mm
    JOIN meters m ON mm.meter_id = m.id
    LEFT JOIN users u ON mm.moved_by_user_id = u.id
    $whereMovement
)
UNION ALL
(
    SELECT
        'AUDIT' AS type,
        NULL,
        al.action,
        NULL,
        u.email,
        al.created_at
    FROM audit_logs al
    LEFT JOIN users u ON al.user_id = u.id
    $whereAudit
)
ORDER BY created_at DESC
LIMIT $limit OFFSET $offset
";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$timeline = $stmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| LOAD LAYOUT
|--------------------------------------------------------------------------
*/
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>

<div class="main-content">

<div class="page-header">
    <h2>System Activity</h2>
    <p class="page-subtitle">Full infrastructure monitoring & audit trace.</p>
</div>

<!-- FILTER BAR -->
<div class="table-wrap" style="margin-bottom:20px;padding:20px;">
<form method="GET" style="display:flex;gap:15px;flex-wrap:wrap;align-items:end;">

    <div>
        <label>Search Meter</label>
        <input type="text" name="meter" value="<?= htmlspecialchars($searchMeter) ?>">
    </div>

    <div>
        <label>Type</label>
        <select name="type">
            <option value="">All</option>
            <option value="MOVEMENT" <?= $typeFilter=='MOVEMENT'?'selected':'' ?>>Movement</option>
            <option value="AUDIT" <?= $typeFilter=='AUDIT'?'selected':'' ?>>Audit</option>
        </select>
    </div>

    <div>
        <button type="submit" class="action-btn">Filter</button>
    </div>

    <div>
        <a href="activity.php" class="action-btn gray">Reset</a>
    </div>

    <div>
        <a href="?export=1" class="action-btn black">Export CSV</a>
    </div>

</form>
</div>

<?php if (empty($timeline)): ?>
<div class="stat-card">No activity found.</div>
<?php endif; ?>

<?php foreach ($timeline as $item): ?>

<div class="stat-card" style="margin-bottom:15px;">

    <div style="display:flex;justify-content:space-between;align-items:center;">

        <div>
            <?php if ($item['type'] === 'MOVEMENT'): ?>
                <span class="status INSTALLED">MOVEMENT</span>
            <?php else: ?>
                <span class="status FAULTY">AUDIT</span>
            <?php endif; ?>
        </div>

        <div class="small">
            <?= htmlspecialchars($item['created_at']) ?>
        </div>
    </div>

    <div style="margin-top:10px;font-weight:600;">
        <?= htmlspecialchars($item['title']) ?>
    </div>

    <?php if ($item['meter_number']): ?>
        <div style="margin-top:5px;">
            Meter: <strong><?= htmlspecialchars($item['meter_number']) ?></strong>
            <a href="inventory.php?search=<?= urlencode($item['meter_number']) ?>" 
               style="margin-left:10px;font-size:12px;">
               View Meter History
            </a>
        </div>
    <?php endif; ?>

    <?php if ($item['description']): ?>
        <div style="margin-top:5px;">
            <?= htmlspecialchars($item['description']) ?>
        </div>
    <?php endif; ?>

    <div class="small" style="margin-top:8px;">
        By: <?= htmlspecialchars($item['user_email'] ?? 'System') ?>
    </div>

</div>

<?php endforeach; ?>

<!-- PAGINATION -->
<div style="margin-top:30px;text-align:center;">
    <?php if ($page > 1): ?>
        <a class="action-btn" href="?page=<?= $page-1 ?>">Previous</a>
    <?php endif; ?>

    <span style="margin:0 15px;">Page <?= $page ?></span>

    <?php if (count($timeline) == $limit): ?>
        <a class="action-btn" href="?page=<?= $page+1 ?>">Next</a>
    <?php endif; ?>
</div>

</div>

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