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

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


$companyId = $_SESSION['company_id'];
$userId    = $_SESSION['user_id'];

/* ===============================
   NORMALIZE TYPE FUNCTION
================================= */
function normalize_type($type) {
    $type = strtolower(trim((string)$type));

    if ($type === '1' || strpos($type, 'cheq') !== false || strpos($type, 'current') !== false) {
        return '1';
    }

    if ($type === '2' || strpos($type, 'sav') !== false) {
        return '2';
    }

    return '1'; // safe default
}

/* ===============================
   HANDLE UPDATE (EXISTING)
================================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_edit'])) {

    $dept   = $_POST['department_code'];
    $bank   = trim($_POST['bank_account']);
    $branch = trim($_POST['branch_code']);
    $type   = trim($_POST['account_type']);

    $stmt = $pdo->prepare("
        UPDATE department_banking_details
        SET bank_account = ?, 
            branch_code = ?, 
            account_type = ?, 
            updated_by = ?, 
            updated_at = NOW()
        WHERE company_id = ? AND department_code = ?
    ");

    $stmt->execute([
        $bank,
        $branch,
        $type,
        $userId,
        $companyId,
        $dept
    ]);

    header("Location: banking.php?updated=1");
    exit;
}

/* ===============================
   ADD NEW ACCOUNT (NEW)
================================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_new'])) {

    $department = trim($_POST['new_department']);
    $bank       = trim($_POST['new_bank']);
    $branch     = trim($_POST['new_branch']);
    $type       = trim($_POST['new_type']);

    if ($department !== '' && $bank !== '' && $branch !== '') {

        $stmt = $pdo->prepare("
            INSERT INTO department_banking_details
            (company_id, department_code, bank_account, branch_code, account_type, updated_by)
            VALUES (?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                bank_account = VALUES(bank_account),
                branch_code  = VALUES(branch_code),
                account_type = VALUES(account_type),
                updated_by   = VALUES(updated_by),
                updated_at   = NOW()
        ");

        $stmt->execute([$companyId, $department, $bank, $branch, $type, $userId]);

        // keep pagination/search when redirecting back
        $params = [];
        if (!empty($_GET['search'])) $params['search'] = $_GET['search'];
        if (!empty($_GET['page'])) $params['page'] = $_GET['page'];

        $url = "banking.php?added=1";
        if (!empty($params)) $url .= "&" . http_build_query($params);

        header("Location: " . $url);
        exit;
    }
}

/* ===============================
   CSV BULK UPLOAD (NEW)
================================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_csv'])) {
$processed = 0;
$inserted  = 0;
$updated   = 0;
$skipped   = 0;
    if (!empty($_FILES['csv_file']['tmp_name'])) {

        $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
        fgetcsv($handle); // skip header row

        while (($row = fgetcsv($handle, 1000, ";")) !== false) {
            $processed++;

            $department = trim($row[0] ?? '');

/* ===============================
   NORMALIZE BANK DATA
================================= */

// clean account number (digits only)
$bank = preg_replace('/\D/', '', $row[1] ?? '');

// normalize branch (always 6 digits)
$branch = str_pad(
    preg_replace('/\D/', '', $row[2] ?? ''),
    6,
    '0',
    STR_PAD_LEFT
);

// normalize account type (1 or 2)
$type = normalize_type($row[3] ?? '');

            if ($department === '' || $bank === '' || $branch === '') {
    $skipped++;
error_log("SKIPPED ROW: " . json_encode($row));
    continue;
}
$check = $pdo->prepare("
    SELECT COUNT(*) 
    FROM department_banking_details 
    WHERE company_id = ? 
    AND department_code = CONVERT(? USING latin1)
");
$check->execute([$companyId, $department]);

$exists = $check->fetchColumn() > 0;
            $stmt = $pdo->prepare("
                INSERT INTO department_banking_details
                (company_id, department_code, bank_account, branch_code, account_type, updated_by)
                VALUES (?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                    bank_account = VALUES(bank_account),
                    branch_code  = VALUES(branch_code),
                    account_type = VALUES(account_type),
                    updated_by   = VALUES(updated_by),
                    updated_at   = NOW()
            ");

            $stmt->execute([$companyId, $department, $bank, $branch, $type, $userId]);
            if ($exists) {
    $updated++;
} else {
    $inserted++;
}
        }

        fclose($handle);

        // keep pagination/search when redirecting back
        $params = [];
        if (!empty($_GET['search'])) $params['search'] = $_GET['search'];
        if (!empty($_GET['page'])) $params['page'] = $_GET['page'];

        $url = "banking.php?csv=1"
     . "&processed={$processed}"
     . "&inserted={$inserted}"
     . "&updated={$updated}"
     . "&skipped={$skipped}";
        if (!empty($params)) $url .= "&" . http_build_query($params);

        header("Location: " . $url);
        exit;
    }
}

/* ===============================
   SEARCH + PAGINATION (UPDATED)
================================= */
$search = trim($_GET['search'] ?? '');
$edit   = $_GET['edit'] ?? null;

$perPage = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $perPage;

$whereSql = " WHERE company_id = ? ";
$params = [$companyId];

if ($search !== '') {
    $whereSql .= " AND (
        department_code LIKE ?
        OR bank_account LIKE ?
        OR branch_code LIKE ?
    ) ";
    $like = '%' . $search . '%';
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}

/* Total rows for pagination */
$stmt = $pdo->prepare("SELECT COUNT(*) FROM department_banking_details " . $whereSql);
$stmt->execute($params);
$totalRows = (int)$stmt->fetchColumn();

$totalPages = (int)ceil(max(1, $totalRows) / $perPage);
if ($page > $totalPages) $page = $totalPages;
$offset = ($page - 1) * $perPage;

/* Fetch current page */
$sql = "
    SELECT *
    FROM department_banking_details
    {$whereSql}
    ORDER BY department_code ASC
    LIMIT {$perPage} OFFSET {$offset}
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* Row count display */
$fromRow = ($totalRows === 0) ? 0 : ($offset + 1);
$toRow   = min($offset + $perPage, $totalRows);

/* Pagination link builder (keeps search) */
function buildBankingUrl(array $extra = []): string {
    $base = 'banking.php';
    $q = [];
    if (!empty($_GET['search'])) $q['search'] = $_GET['search'];
    if (!empty($_GET['edit'])) $q['edit'] = $_GET['edit'];
    foreach ($extra as $k => $v) $q[$k] = $v;
    return $base . (!empty($q) ? ('?' . http_build_query($q)) : '');
}
?>

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

<div class="container">

    <div class="page-header">
        <h2>Banking Management</h2>
    </div>

    <?php if (isset($_GET['updated'])): ?>
        <div style="background:#dff3e3;padding:10px;margin-bottom:15px;">
            Banking details updated successfully.
        </div>
    <?php endif; ?>

    <?php if (isset($_GET['added'])): ?>
        <div style="background:#dff3e3;padding:10px;margin-bottom:15px;">
            New account added successfully.
        </div>
    <?php endif; ?>

    <?php if (isset($_GET['csv'])): ?>
    <div style="background:#dff3e3;padding:10px;margin-bottom:15px;">
        <strong>CSV Upload Summary:</strong><br><br>

        Processed: <?= $_GET['processed'] ?? 0 ?><br>
        Inserted: <?= $_GET['inserted'] ?? 0 ?><br>
        Updated: <?= $_GET['updated'] ?? 0 ?><br>
        Skipped: <?= $_GET['skipped'] ?? 0 ?><br>
    </div>
<?php endif; ?>

    <!-- SEARCH (EXISTING) -->
    <form method="get" class="banking-toolbar">
        <input type="text" name="search"
               placeholder="Search Department / Bank / Branch"
               value="<?= htmlspecialchars($search) ?>">
        <button type="submit" class="btn">Search</button>
        <a href="banking.php" class="btn">Reset</a>
    </form>

    <!-- CSV UPLOAD (NEW) -->
    <div class="card banking-card">
        <h3>Bulk Upload Banking (CSV)</h3>
        <form method="post" enctype="multipart/form-data" class="banking-upload">
            <input type="file" name="csv_file" accept=".csv" required>
            <button type="submit" name="upload_csv" class="btn primary">
                Upload CSV
            </button>
        </form>
        <small>Format: department_code, bank_account, branch_code, account_type</small>
    </div>

    <div class="banking-meta">
        <div><strong>Rows:</strong> <?= $totalRows ?><?= $search !== '' ? " (filtered)" : "" ?></div>
        <div><strong>Showing:</strong> <?= $fromRow ?>–<?= $toRow ?> of <?= $totalRows ?></div>
    </div>

    <div class="table-wrap">
        <table class="banking-table">
            <thead>
                <tr>
                    <th>Department</th>
                    <th>Bank Account</th>
                    <th>Branch</th>
                    <th>Type</th>
                    <th>Updated</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>

            <!-- ADD NEW ROW (MOVED TO TOP) -->
            <tr class="banking-add-row">
                <form method="post">
                    <td><input type="text" name="new_department" placeholder="New Dept Code (e.g. EDMCD999)"></td>
                    <td><input type="text" name="new_bank" placeholder="Bank Account"></td>
                    <td><input type="text" name="new_branch" placeholder="Branch Code"></td>
                    <td>
                        <select name="new_type">
                            <option value="">Type</option>
                            <option value="1">1</option>
                            <option value="2">2</option>
                        </select>
                    </td>
                    <td>-</td>
                    <td><button name="add_new" class="btn">Add</button></td>
                </form>
            </tr>

            <?php foreach ($rows as $r): ?>
                <tr>

                <?php if ($edit === $r['department_code']): ?>

                    <!-- EDIT MODE -->
                    <form method="post">
                        <td>
                            <?= htmlspecialchars($r['department_code']) ?>
                            <input type="hidden"
                                   name="department_code"
                                   value="<?= htmlspecialchars($r['department_code']) ?>">
                        </td>

                        <td>
                            <input type="text"
                                   name="bank_account"
                                   value="<?= htmlspecialchars($r['bank_account']) ?>">
                        </td>

                        <td>
                            <input type="text"
                                   name="branch_code"
                                   value="<?= htmlspecialchars($r['branch_code']) ?>">
                        </td>

                        <td>
                            <select name="account_type">
                                <option value="1" <?= $r['account_type']=='1'?'selected':'' ?>>1</option>
                                <option value="2" <?= $r['account_type']=='2'?'selected':'' ?>>2</option>
                            </select>
                        </td>

                        <td><?= htmlspecialchars($r['updated_at']) ?></td>

                        <td class="banking-actions">
                            <button type="submit"
                                    name="save_edit"
                                    class="btn primary">
                                Save
                            </button>
                            <a href="<?= buildBankingUrl(['page'=>$page]) ?>" class="btn">Cancel</a>
                        </td>
                    </form>

                <?php else: ?>

                    <!-- NORMAL MODE -->
                    <td><?= htmlspecialchars($r['department_code']) ?></td>
                    <td><?= htmlspecialchars($r['bank_account']) ?></td>
                    <td><?= htmlspecialchars($r['branch_code']) ?></td>
                    <td><?= htmlspecialchars($r['account_type'] ?? '') ?></td>
<td><?= htmlspecialchars($r['updated_at'] ?? '') ?></td>
                    <td class="banking-actions">
                        <a href="<?= buildBankingUrl(['edit'=> $r['department_code'], 'page'=> $page]) ?>" class="btn">
                            Edit
                        </a>
                    </td>

                <?php endif; ?>

                </tr>
            <?php endforeach; ?>

            <?php if (empty($rows)): ?>
                <tr>
                    <td colspan="6" style="padding:14px;">No records found.</td>
                </tr>
            <?php endif; ?>

            </tbody>
        </table>
    </div>

    <!-- PAGINATION -->
    <?php if ($totalPages > 1): ?>
        <div class="banking-pagination">
            <a class="btn" href="<?= buildBankingUrl(['page'=> max(1, $page-1)]) ?>">&laquo; Prev</a>

            <?php
                // show a small window of pages
                $start = max(1, $page - 3);
                $end   = min($totalPages, $page + 3);
                for ($p = $start; $p <= $end; $p++):
            ?>
                <a class="btn <?= ($p === $page) ? 'primary' : '' ?>"
                   href="<?= buildBankingUrl(['page'=> $p]) ?>">
                    <?= $p ?>
                </a>
            <?php endfor; ?>

            <a class="btn" href="<?= buildBankingUrl(['page'=> min($totalPages, $page+1)]) ?>">Next &raquo;</a>

            <span class="banking-pageinfo">Page <?= $page ?> of <?= $totalPages ?></span>
        </div>
    <?php endif; ?>

</div>



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