<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Bank Details';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('table_exists')) {
    function table_exists(PDO $pdo, string $table): bool
    {
        try {
            $stmt = $pdo->prepare("SHOW TABLES LIKE :table_name");
            $stmt->execute([':table_name' => $table]);
            return (bool)$stmt->fetchColumn();
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('fetch_currencies')) {
    function fetch_currencies(PDO $pdo): array
    {
        try {
            $stmt = $pdo->query("\n                SELECT CurrencyID, CurrencyCode, Currency\n                FROM tblcurrency\n                WHERE status = 1\n                ORDER BY order_no ASC, CurrencyCode ASC\n            ");
            return $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
        } catch (Throwable $e) {
            return [];
        }
    }
}

if (!function_exists('fetch_properties')) {
    function fetch_properties(PDO $pdo): array
    {
        try {
            $stmt = $pdo->query("
                SELECT id, name
                FROM properties
                ORDER BY name ASC
            ");
            return $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
        } catch (Throwable $e) {
            return [];
        }
    }
}

$form = [
    'ID' => 0,
    'property_id' => '',
    'AccountName' => '',
    'Bank' => '',
    'Branch' => '',
    'SwiftCode' => '',
    'BranchCode' => '',
    'AccountNo' => '',
    'Currency' => '',
    'PaymentMemo' => '',
    'ProvisionalInstruction' => '',
    'ProvisionalContent' => '',
    'bank_status' => '1',
];

$errors = [];
$success = '';
$editing = false;

if (isset($_GET['saved']) && (int)$_GET['saved'] === 1) {
    $success = 'Bank details saved successfully.';
}
if (isset($_GET['deleted']) && (int)$_GET['deleted'] === 1) {
    $success = 'Bank details deleted successfully.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_bank'])) {
    $form['ID'] = (int)($_POST['ID'] ?? 0);
    $form['property_id'] = trim((string)($_POST['property_id'] ?? ''));
    $form['AccountName'] = trim((string)($_POST['AccountName'] ?? ''));
    $form['Bank'] = trim((string)($_POST['Bank'] ?? ''));
    $form['Branch'] = trim((string)($_POST['Branch'] ?? ''));
    $form['SwiftCode'] = trim((string)($_POST['SwiftCode'] ?? ''));
    $form['BranchCode'] = trim((string)($_POST['BranchCode'] ?? ''));
    $form['AccountNo'] = trim((string)($_POST['AccountNo'] ?? ''));
    $form['Currency'] = trim((string)($_POST['Currency'] ?? ''));
    $form['PaymentMemo'] = trim((string)($_POST['PaymentMemo'] ?? ''));
    $form['ProvisionalInstruction'] = trim((string)($_POST['ProvisionalInstruction'] ?? ''));
    $form['ProvisionalContent'] = trim((string)($_POST['ProvisionalContent'] ?? ''));
    $form['bank_status'] = (string)((int)($_POST['bank_status'] ?? 1));

    $editing = $form['ID'] > 0;

    if ($form['AccountName'] === '') {
        $errors[] = 'Account name is required.';
    }
    if ($form['Bank'] === '') {
        $errors[] = 'Bank name is required.';
    }
    if ($form['Branch'] === '') {
        $errors[] = 'Branch is required.';
    }
    if ($form['AccountNo'] === '') {
        $errors[] = 'Account number is required.';
    }

    if (!$errors) {
        try {
            if ($editing) {
                $stmt = $pdo->prepare("\n                    UPDATE tblbankdetails\n                    SET property_id = :property_id,\n                        AccountName = :AccountName,\n                        Bank = :Bank,\n                        Branch = :Branch,\n                        SwiftCode = :SwiftCode,\n                        BranchCode = :BranchCode,\n                        AccountNo = :AccountNo,\n                        Currency = :Currency,\n                        PaymentMemo = :PaymentMemo,\n                        ProvisionalInstruction = :ProvisionalInstruction,\n                        ProvisionalContent = :ProvisionalContent,\n                        bank_status = :bank_status\n                    WHERE ID = :ID\n                ");
                $stmt->execute([
                    ':property_id' => $form['property_id'] !== '' ? (int)$form['property_id'] : null,
                    ':AccountName' => $form['AccountName'],
                    ':Bank' => $form['Bank'],
                    ':Branch' => $form['Branch'],
                    ':SwiftCode' => $form['SwiftCode'] !== '' ? $form['SwiftCode'] : null,
                    ':BranchCode' => $form['BranchCode'] !== '' ? $form['BranchCode'] : null,
                    ':AccountNo' => $form['AccountNo'],
                    ':Currency' => $form['Currency'] !== '' ? (int)$form['Currency'] : null,
                    ':PaymentMemo' => $form['PaymentMemo'] !== '' ? $form['PaymentMemo'] : null,
                    ':ProvisionalInstruction' => $form['ProvisionalInstruction'] !== '' ? $form['ProvisionalInstruction'] : null,
                    ':ProvisionalContent' => $form['ProvisionalContent'] !== '' ? $form['ProvisionalContent'] : null,
                    ':bank_status' => (int)$form['bank_status'],
                    ':ID' => (int)$form['ID'],
                ]);
            } else {
                $stmt = $pdo->prepare("\n                    INSERT INTO tblbankdetails\n                    (\n                        property_id, AccountName, Bank, Branch, SwiftCode, BranchCode,\n                        AccountNo, Currency, PaymentMemo, ProvisionalInstruction,\n                        ProvisionalContent, bank_status\n                    )\n                    VALUES\n                    (\n                        :property_id, :AccountName, :Bank, :Branch, :SwiftCode, :BranchCode,\n                        :AccountNo, :Currency, :PaymentMemo, :ProvisionalInstruction,\n                        :ProvisionalContent, :bank_status\n                    )\n                ");
                $stmt->execute([
                    ':property_id' => $form['property_id'] !== '' ? (int)$form['property_id'] : null,
                    ':AccountName' => $form['AccountName'],
                    ':Bank' => $form['Bank'],
                    ':Branch' => $form['Branch'],
                    ':SwiftCode' => $form['SwiftCode'] !== '' ? $form['SwiftCode'] : null,
                    ':BranchCode' => $form['BranchCode'] !== '' ? $form['BranchCode'] : null,
                    ':AccountNo' => $form['AccountNo'],
                    ':Currency' => $form['Currency'] !== '' ? (int)$form['Currency'] : null,
                    ':PaymentMemo' => $form['PaymentMemo'] !== '' ? $form['PaymentMemo'] : null,
                    ':ProvisionalInstruction' => $form['ProvisionalInstruction'] !== '' ? $form['ProvisionalInstruction'] : null,
                    ':ProvisionalContent' => $form['ProvisionalContent'] !== '' ? $form['ProvisionalContent'] : null,
                    ':bank_status' => (int)$form['bank_status'],
                ]);
            }

            header('Location: banks.php?saved=1');
            exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

if (isset($_GET['delete']) && (int)$_GET['delete'] > 0) {
    try {
        $stmt = $pdo->prepare("DELETE FROM tblbankdetails WHERE ID = :ID");
        $stmt->execute([':ID' => (int)$_GET['delete']]);
        header('Location: banks.php?deleted=1');
        exit;
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

if (isset($_GET['edit']) && (int)$_GET['edit'] > 0) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM tblbankdetails WHERE ID = :ID LIMIT 1");
        $stmt->execute([':ID' => (int)$_GET['edit']]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $editing = true;
            $form = [
                'ID' => (int)$row['ID'],
                'property_id' => (string)($row['property_id'] ?? ''),
                'AccountName' => (string)$row['AccountName'],
                'Bank' => (string)$row['Bank'],
                'Branch' => (string)$row['Branch'],
                'SwiftCode' => (string)($row['SwiftCode'] ?? ''),
                'BranchCode' => (string)($row['BranchCode'] ?? ''),
                'AccountNo' => (string)$row['AccountNo'],
                'Currency' => (string)($row['Currency'] ?? ''),
                'PaymentMemo' => (string)($row['PaymentMemo'] ?? ''),
                'ProvisionalInstruction' => (string)($row['ProvisionalInstruction'] ?? ''),
                'ProvisionalContent' => (string)($row['ProvisionalContent'] ?? ''),
                'bank_status' => (string)(int)$row['bank_status'],
            ];
        } else {
            $errors[] = 'Bank record not found.';
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

$currencies = fetch_currencies($pdo);
$properties = fetch_properties($pdo);

$currencyMap = [];
foreach ($currencies as $c) {
    $currencyMap[(string)$c['CurrencyID']] = trim(($c['CurrencyCode'] ?? '') . ' - ' . ($c['Currency'] ?? ''));
}

$propertyMap = [];
foreach ($properties as $p) {
    $propertyMap[(string)$p['id']] = $p['name'];
}

$search = trim((string)($_GET['q'] ?? ''));
$statusFilter = trim((string)($_GET['status'] ?? ''));

$sql = "\n    SELECT b.*, cur.CurrencyCode, cur.Currency AS CurrencyName\n    FROM tblbankdetails b\n    LEFT JOIN tblcurrency cur ON cur.CurrencyID = b.Currency\n    WHERE 1=1\n";
$params = [];

if ($search !== '') {
    $sql .= "\n        AND (\n            b.AccountName LIKE :search\n            OR b.Bank LIKE :search\n            OR b.Branch LIKE :search\n            OR b.AccountNo LIKE :search\n            OR b.SwiftCode LIKE :search\n            OR b.BranchCode LIKE :search\n            OR b.PaymentMemo LIKE :search\n        )\n    ";
    $params[':search'] = '%' . $search . '%';
}

if ($statusFilter !== '' && in_array($statusFilter, ['0', '1'], true)) {
    $sql .= " AND b.bank_status = :bank_status ";
    $params[':bank_status'] = (int)$statusFilter;
}

$sql .= " ORDER BY b.bank_status DESC, b.Bank ASC, b.AccountName ASC ";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $banks = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $banks = [];
    $errors[] = $e->getMessage();
}

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

<style>
.bank-hero {
    background: linear-gradient(135deg, #2f343a, #5c636b);
    color: #fff;
    border-radius: 18px;
    padding: 18px 22px;
    margin-bottom: 18px;
    box-shadow: 0 10px 26px rgba(15, 23, 42, .12);
}
.bank-hero-title {
    font-size: 1.45rem;
    font-weight: 800;
    letter-spacing: -.02em;
}
.bank-hero-subtitle {
    color: rgba(255,255,255,.78);
    font-size: .92rem;
}
.form-section, .panel-card {
    border: 1px solid #e5e7eb;
    border-radius: 18px;
    background: #fff;
    box-shadow: 0 10px 24px rgba(15, 23, 42, .06);
}
.form-section {
    padding: 18px;
}
.form-section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 800;
    font-size: 1rem;
    margin-bottom: 14px;
    color: #1f2937;
}
.table-modern thead th {
    position: sticky;
    top: 0;
    background: #f8fafc;
    z-index: 2;
    font-size: .78rem;
    text-transform: uppercase;
    letter-spacing: .04em;
    color: #475569;
    border-bottom: 1px solid #e5e7eb;
}
.table-modern td {
    vertical-align: middle;
    font-size: .92rem;
}
.bank-table-wrap {
    max-height: 620px;
    overflow: auto;
}
.small-muted {
    color: #64748b;
    font-size: .78rem;
}
</style>

<div class="bank-hero">
    <div class="row align-items-center g-3">
        <div class="col-lg-8">
            <div class="small text-white-50"><i class="bi bi-bank me-1"></i> Setup</div>
            <div class="bank-hero-title">Bank Details</div>
            <div class="bank-hero-subtitle">Maintain bank accounts used on invoices, proformas, receipts and payment instructions.</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="banks.php" class="btn btn-outline-light">
                <i class="bi bi-plus-circle me-2"></i>New Bank Account
            </a>
        </div>
    </div>
</div>

<?php if ($success): ?>
    <div class="alert alert-success"><?php echo h($success); ?></div>
<?php endif; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-xl-5">
        <div class="form-section">
            <div class="form-section-title">
                <i class="bi bi-credit-card-2-front"></i>
                <?php echo $editing ? 'Edit Bank Account' : 'New Bank Account'; ?>
            </div>

            <form method="post" class="row g-3">
                <input type="hidden" name="ID" value="<?php echo (int)$form['ID']; ?>">

                <div class="col-md-6">
                    <label class="form-label">Property</label>
                    <select name="property_id" class="form-select">
                        <option value="">General / All Properties</option>
                        <?php foreach ($properties as $p): ?>
                            <option value="<?php echo (int)$p['id']; ?>" <?php echo (string)$form['property_id'] === (string)$p['id'] ? 'selected' : ''; ?>>
                                <?php echo h($p['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (!$properties): ?>
                        <div class="form-text text-danger">No properties found in the properties table.</div>
                    <?php endif; ?>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Status</label>
                    <select name="bank_status" class="form-select">
                        <option value="1" <?php echo $form['bank_status'] === '1' ? 'selected' : ''; ?>>Active</option>
                        <option value="0" <?php echo $form['bank_status'] === '0' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Account Name</label>
                    <input type="text" name="AccountName" class="form-control" value="<?php echo h($form['AccountName']); ?>" maxlength="100" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Bank</label>
                    <input type="text" name="Bank" class="form-control" value="<?php echo h($form['Bank']); ?>" maxlength="45" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Branch</label>
                    <input type="text" name="Branch" class="form-control" value="<?php echo h($form['Branch']); ?>" maxlength="45" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Account No</label>
                    <input type="text" name="AccountNo" class="form-control" value="<?php echo h($form['AccountNo']); ?>" maxlength="45" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Currency</label>
                    <select name="Currency" class="form-select">
                        <option value="">Select currency</option>
                        <?php foreach ($currencies as $c): ?>
                            <option value="<?php echo (int)$c['CurrencyID']; ?>" <?php echo (string)$form['Currency'] === (string)$c['CurrencyID'] ? 'selected' : ''; ?>>
                                <?php echo h(trim(($c['CurrencyCode'] ?? '') . ' - ' . ($c['Currency'] ?? ''))); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Swift Code</label>
                    <input type="text" name="SwiftCode" class="form-control" value="<?php echo h($form['SwiftCode']); ?>" maxlength="45">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Branch Code</label>
                    <input type="text" name="BranchCode" class="form-control" value="<?php echo h($form['BranchCode']); ?>" maxlength="45">
                </div>

                <div class="col-12">
                    <label class="form-label">Payment Memo</label>
                    <textarea name="PaymentMemo" class="form-control" rows="2" maxlength="600" placeholder="Example: Please quote invoice number as payment reference."><?php echo h($form['PaymentMemo']); ?></textarea>
                </div>

                <div class="col-12">
                    <label class="form-label">Provisional Instruction</label>
                    <textarea name="ProvisionalInstruction" class="form-control" rows="2" maxlength="600"><?php echo h($form['ProvisionalInstruction']); ?></textarea>
                </div>

                <div class="col-12">
                    <label class="form-label">Provisional Content</label>
                    <textarea name="ProvisionalContent" class="form-control" rows="3" maxlength="1200"><?php echo h($form['ProvisionalContent']); ?></textarea>
                </div>

                <div class="col-12 d-flex gap-2">
                    <button type="submit" name="save_bank" value="1" class="btn btn-primary">
                        <i class="bi bi-save me-2"></i><?php echo $editing ? 'Update Bank' : 'Save Bank'; ?>
                    </button>
                    <a href="banks.php" class="btn btn-light">Reset</a>
                </div>
            </form>
        </div>
    </div>

    <div class="col-xl-7">
        <div class="card panel-card">
            <div class="card-header bg-white">
                <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
                    <h5 class="mb-0">Bank Accounts</h5>
                    <form method="get" class="d-flex flex-wrap gap-2">
                        <input type="text" name="q" class="form-control" placeholder="Search banks..." value="<?php echo h($search); ?>" style="min-width:220px;">
                        <select name="status" class="form-select" style="width:150px;">
                            <option value="" <?php echo $statusFilter === '' ? 'selected' : ''; ?>>All</option>
                            <option value="1" <?php echo $statusFilter === '1' ? 'selected' : ''; ?>>Active</option>
                            <option value="0" <?php echo $statusFilter === '0' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                        <button class="btn btn-outline-secondary">Search</button>
                    </form>
                </div>
            </div>

            <div class="card-body p-0">
                <div class="table-responsive bank-table-wrap">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Bank Account</th>
                                <th>Account No</th>
                                <th>Currency</th>
                                <th>Property</th>
                                <th>Status</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$banks): ?>
                                <tr>
                                    <td colspan="7" class="text-center text-muted py-4">No bank accounts found.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($banks as $row): ?>
                                    <tr>
                                        <td><?php echo (int)$row['ID']; ?></td>
                                        <td>
                                            <div class="fw-semibold"><?php echo h($row['Bank']); ?></div>
                                            <div class="small-muted"><?php echo h($row['AccountName']); ?></div>
                                            <div class="small-muted"><?php echo h($row['Branch']); ?></div>
                                        </td>
                                        <td>
                                            <div><?php echo h($row['AccountNo']); ?></div>
                                            <?php if (!empty($row['SwiftCode']) || !empty($row['BranchCode'])): ?>
                                                <div class="small-muted">
                                                    <?php if (!empty($row['SwiftCode'])): ?>SWIFT: <?php echo h($row['SwiftCode']); ?><?php endif; ?>
                                                    <?php if (!empty($row['BranchCode'])): ?> Branch Code: <?php echo h($row['BranchCode']); ?><?php endif; ?>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo h($row['CurrencyCode'] ?? ''); ?></td>
                                        <td><?php echo h(($row['property_name'] ?? '') !== '' ? $row['property_name'] : 'General'); ?></td>
                                        <td>
                                            <?php if ((int)$row['bank_status'] === 1): ?>
                                                <span class="badge text-bg-success">Active</span>
                                            <?php else: ?>
                                                <span class="badge text-bg-secondary">Inactive</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end">
                                            <div class="d-inline-flex gap-2">
                                                <a href="banks.php?edit=<?php echo (int)$row['ID']; ?>" class="btn btn-sm btn-primary">Edit</a>
                                                <a href="banks.php?delete=<?php echo (int)$row['ID']; ?>"
                                                   class="btn btn-sm btn-outline-danger"
                                                   onclick="return confirm('Delete this bank account?');">
                                                    Delete
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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