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

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

$companyId = $_SESSION['company_id'];

$runId = (int)($_GET['run_id'] ?? 0);

if ($runId <= 0) {
    die("Invalid run.");
}

/* LOAD RUN */
$stmt = $pdo->prepare("
    SELECT *
    FROM settlement_runs
    WHERE id = ? AND company_id = ?
    LIMIT 1
");

$stmt->execute([$runId, $companyId]);
$run = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$run) {
    die("Run not found.");
}

/* ===============================
   FILTER + SEARCH (MATCH VIEW)
================================= */

$search = $_GET['search'] ?? '';
$statusFilter = $_GET['status_filter'] ?? '';

$query = "
    SELECT *
    FROM settlement_records
    WHERE run_id = ?
";

$params = [$runId];

/* STATUS FILTER */
if ($statusFilter !== '') {
    $query .= " AND status = ?";
    $params[] = $statusFilter;
} else {
    // default: only READY
    $query .= " AND status = 'READY'";
}

/* SEARCH FILTER */
if ($search !== '') {
    $query .= " AND (
        department_full LIKE ?
        OR bank_account LIKE ?
        OR branch_code LIKE ?
    )";

    $searchParam = "%$search%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
}

$stmt = $pdo->prepare($query);
$stmt->execute($params);

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$rows) {
    die("No records to export.");
}

if (!$rows) {
    die("No READY records to export.");
}

/* DOWNLOAD HEADERS */
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="netcash_run_'.$runId.'.csv"');

$output = fopen('php://output', 'w');

/* ===============================
   NETCASH HEADER (MATCH YOUR FILE)
================================= */
fputcsv($output, [
    'Account reference',
    'Account name',
    'Bank account holder name',
    'Bank account type',
    'Bank account branch',
    'Bank account number',
    'Amount',
    'Beneficiary statement reference'
], ';');

/* ===============================
   DATA
================================= */
foreach ($rows as $row) {

    $reference = $row['department_code'];
    $name      = $row['department_full'];

    fputcsv($output, [
        $reference,                      // Account reference
        $name,                           // Account name
        $name,                           // Account holder
        $row['account_type'],            // 1 or 2
        $row['branch_code'],
        $row['bank_account'],
        number_format((float)$row['payable'], 2, '.', ''),
        'EDM Rebate Payment'             // Static reference (like your file)
    ], ';');
}

fclose($output);
exit;