<?php
require_once '../includes/auth.php';
require_once '../db.php';

// Resolve which company we're managing bank accounts for.
// Priority: GET param > POST param > active session company
$company_id = (int)(
    $_GET['company_id']  ??
    $_POST['company_id'] ??
    $_SESSION['active_company_id'] ??
    0
);

// Ensure the company_bank_accounts table has a company_id column (migration guard)
$conn->query("CREATE TABLE IF NOT EXISTS company_bank_accounts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    company_id INT NOT NULL DEFAULT 0,
    bank_name VARCHAR(100) NOT NULL,
    account_holder VARCHAR(100) DEFAULT '',
    account_no VARCHAR(50) NOT NULL,
    ifsc VARCHAR(20) DEFAULT '',
    branch VARCHAR(100) DEFAULT '',
    account_type VARCHAR(50) DEFAULT 'Savings',
    upi_id VARCHAR(100) DEFAULT '',
    upi_name VARCHAR(100) DEFAULT '',
    is_primary TINYINT(1) DEFAULT 0,
    display_on_invoice TINYINT(1) DEFAULT 1,
    sort_order INT DEFAULT 0
)");

// Add company_id column if it's missing (upgrade path)
$colCheck = $conn->query("SHOW COLUMNS FROM company_bank_accounts LIKE 'company_id'");
if ($colCheck && $colCheck->num_rows === 0) {
    $conn->query("ALTER TABLE company_bank_accounts ADD COLUMN company_id INT NOT NULL DEFAULT 0 AFTER id");
    // Assign existing rows to the first company
    $firstCo = $conn->query("SELECT id FROM company_master ORDER BY id ASC LIMIT 1")->fetch_row();
    if ($firstCo) {
        $conn->query("UPDATE company_bank_accounts SET company_id = {$firstCo[0]} WHERE company_id = 0");
    }
}

// Load the company record for display context
$companyRec = null;
if ($company_id > 0) {
    $companyRec = $conn->query("SELECT id, company_name FROM company_master WHERE id = $company_id LIMIT 1")->fetch_assoc();
}
// Fallback to first company if still null
if (!$companyRec) {
    $companyRec = $conn->query("SELECT id, company_name FROM company_master ORDER BY id ASC LIMIT 1")->fetch_assoc();
    if ($companyRec) { $company_id = (int)$companyRec['id']; }
}

$action = $_GET['action'] ?? 'list';
$editId = (int)($_GET['id'] ?? 0);

// ── Handle POST (add / edit) ─────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bank_name          = trim($_POST['bank_name']    ?? '');
    $account_holder     = trim($_POST['account_holder'] ?? '');
    $account_no         = trim($_POST['account_no']   ?? '');
    $ifsc               = strtoupper(trim($_POST['ifsc'] ?? ''));
    $branch             = trim($_POST['branch']       ?? '');
    $account_type       = trim($_POST['account_type'] ?? 'Savings');
    $upi_id             = trim($_POST['upi_id']       ?? '');
    $upi_name           = trim($_POST['upi_name']     ?? '');
    $is_primary         = isset($_POST['is_primary']) ? 1 : 0;
    $display_on_invoice = isset($_POST['display_on_invoice']) ? 1 : 0;
    $sort_order         = (int)($_POST['sort_order']  ?? 0);
    $post_company_id    = (int)($_POST['company_id']  ?? $company_id);

    if ($is_primary) {
        // Clear primary flag only within same company
        $conn->query("UPDATE company_bank_accounts SET is_primary = 0 WHERE company_id = $post_company_id");
    }

    if ($editId > 0) {
        $stmt = $conn->prepare(
            "UPDATE company_bank_accounts
             SET bank_name=?, account_holder=?, account_no=?, ifsc=?, branch=?,
                 account_type=?, upi_id=?, upi_name=?, is_primary=?,
                 display_on_invoice=?, sort_order=?, company_id=?
             WHERE id=?"
        );
        $stmt->bind_param(
            "ssssssssiiiii",
            $bank_name, $account_holder, $account_no, $ifsc, $branch,
            $account_type, $upi_id, $upi_name, $is_primary,
            $display_on_invoice, $sort_order, $post_company_id, $editId
        );
    } else {
        $stmt = $conn->prepare(
            "INSERT INTO company_bank_accounts
                (company_id, bank_name, account_holder, account_no, ifsc, branch,
                 account_type, upi_id, upi_name, is_primary, display_on_invoice, sort_order)
             VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"
        );
        $stmt->bind_param(
            "issssssssiii",
            $post_company_id, $bank_name, $account_holder, $account_no, $ifsc, $branch,
            $account_type, $upi_id, $upi_name, $is_primary, $display_on_invoice, $sort_order
        );
    }
    $stmt->execute();

    $redirect = "bank_accounts.php?saved=1";
    if ($post_company_id > 0) { $redirect .= "&company_id=$post_company_id"; }
    header("Location: $redirect");
    exit;
}

// ── Handle delete ────────────────────────────────────────────────────────────
if ($action === 'delete' && $editId > 0) {
    $conn->query("DELETE FROM company_bank_accounts WHERE id = $editId");
    $redirect = "bank_accounts.php?deleted=1";
    if ($company_id > 0) { $redirect .= "&company_id=$company_id"; }
    header("Location: $redirect");
    exit;
}

// ── Load record for edit ─────────────────────────────────────────────────────
$editRec = null;
if (($action === 'edit') && $editId > 0) {
    $editRec = $conn->query("SELECT * FROM company_bank_accounts WHERE id = $editId LIMIT 1")->fetch_assoc();
    if ($editRec) {
        // Sync company_id from the record being edited
        $company_id = (int)$editRec['company_id'];
        $companyRec = $conn->query("SELECT id, company_name FROM company_master WHERE id = $company_id LIMIT 1")->fetch_assoc();
    }
}

// ── List query filtered by company ──────────────────────────────────────────
if ($company_id > 0) {
    $banks = $conn->query("SELECT * FROM company_bank_accounts WHERE company_id = $company_id ORDER BY is_primary DESC, sort_order ASC, id ASC");
} else {
    $banks = $conn->query("SELECT * FROM company_bank_accounts ORDER BY company_id ASC, is_primary DESC, sort_order ASC, id ASC");
}

// Company list for switcher dropdown
$allCompanies = $conn->query("SELECT id, company_name FROM company_master ORDER BY company_name ASC")->fetch_all(MYSQLI_ASSOC);
$isAdmin = ($_SESSION['user_role'] ?? '') === 'admin';

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

<div class="page-header">
    <h2>
        <i class="fas fa-university" style="color:var(--primary);margin-right:8px;"></i>
        Bank Accounts
        <?php if ($companyRec): ?>
        <span style="font-size:14px;font-weight:400;color:var(--text-muted);margin-left:8px;">
            — <?= htmlspecialchars($companyRec['company_name']) ?>
        </span>
        <?php endif; ?>
    </h2>
    <div style="display:flex;align-items:center;gap:10px;">
        <?php if ($isAdmin && count($allCompanies) > 1): ?>
        <form method="get" style="display:flex;align-items:center;gap:6px;">
            <label style="font-size:12px;color:var(--text-muted);white-space:nowrap;">Switch company:</label>
            <select name="company_id" onchange="this.form.submit()" style="padding:6px 10px;font-size:13px;border-radius:6px;border:1px solid var(--border);">
                <?php foreach ($allCompanies as $ac): ?>
                <option value="<?= $ac['id'] ?>" <?= $ac['id'] == $company_id ? 'selected' : '' ?>>
                    <?= htmlspecialchars($ac['company_name']) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </form>
        <?php endif; ?>

        <?php if ($action !== 'add' && $action !== 'edit'): ?>
        <a href="?action=add&company_id=<?= $company_id ?>" class="btn btn-primary">
            <i class="fas fa-plus"></i> Add Bank Account
        </a>
        <?php endif; ?>
    </div>
</div>

<?php if (isset($_GET['saved'])): ?>
<div class="alert alert-success"><i class="fas fa-check-circle"></i> Bank account saved.</div>
<?php elseif (isset($_GET['deleted'])): ?>
<div class="alert alert-warning"><i class="fas fa-trash"></i> Bank account deleted.</div>
<?php endif; ?>

<?php if ($action === 'add' || $action === 'edit'): ?>
<div class="panel" style="max-width:720px;margin-bottom:20px;">
    <div class="panel-header">
        <span class="panel-title"><?= $action === 'edit' ? 'Edit' : 'Add' ?> Bank Account</span>
    </div>
    <div class="panel-body">
        <form method="post">
        <input type="hidden" name="company_id" value="<?= $company_id ?>">

        <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
            <div class="form-group">
                <label>Bank Name <span style="color:var(--danger)">*</span></label>
                <input type="text" id="bankNameInput" name="bank_name" required
                       value="<?= htmlspecialchars($editRec['bank_name'] ?? '') ?>">
            </div>
            <div class="form-group">
                <label>Account Holder Name</label>
                <input type="text" name="account_holder"
                       value="<?= htmlspecialchars($editRec['account_holder'] ?? '') ?>">
            </div>
            <div class="form-group">
                <label>Account Number <span style="color:var(--danger)">*</span></label>
                <input type="text" name="account_no" required
                       value="<?= htmlspecialchars($editRec['account_no'] ?? '') ?>">
            </div>
            <div class="form-group">
                <label>Account Type</label>
                <select name="account_type">
                    <?php foreach (['Savings','Current','OD','CC'] as $t): ?>
                    <option value="<?= $t ?>" <?= ($editRec['account_type'] ?? 'Savings') === $t ? 'selected' : '' ?>>
                        <?= $t ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>IFSC Code</label>
                <div style="display:flex;gap:6px;align-items:center;">
                    <input type="text" id="ifscInput" name="ifsc" style="text-transform:uppercase;"
                           value="<?= htmlspecialchars($editRec['ifsc'] ?? '') ?>"
                           placeholder="e.g. SBIN0001234" maxlength="11">
                    <span id="ifscSpinner" style="display:none;font-size:12px;color:var(--text-muted);white-space:nowrap;">
                        <i class="fas fa-circle-notch fa-spin"></i> Fetching…
                    </span>
                    <span id="ifscError" style="display:none;font-size:12px;color:var(--danger);white-space:nowrap;">Not found</span>
                </div>
            </div>
            <div class="form-group">
                <label>Branch</label>
                <input type="text" id="branchInput" name="branch"
                       value="<?= htmlspecialchars($editRec['branch'] ?? '') ?>">
            </div>
            <div class="form-group">
                <label>UPI ID</label>
                <input type="text" name="upi_id" placeholder="example@upi"
                       value="<?= htmlspecialchars($editRec['upi_id'] ?? '') ?>">
            </div>
            <div class="form-group">
                <label>UPI Display Name</label>
                <input type="text" name="upi_name"
                       value="<?= htmlspecialchars($editRec['upi_name'] ?? '') ?>">
            </div>
            <div class="form-group">
                <label>Sort Order</label>
                <input type="number" name="sort_order"
                       value="<?= $editRec['sort_order'] ?? 0 ?>"
                       style="max-width:100px;">
            </div>
            <div class="form-group" style="display:flex;flex-direction:column;gap:10px;padding-top:20px;">
                <label style="display:flex;align-items:center;gap:8px;font-weight:500;text-transform:none;letter-spacing:0;cursor:pointer;">
                    <input type="checkbox" name="is_primary" <?= !empty($editRec['is_primary']) ? 'checked' : '' ?>>
                    Set as Primary (shown first)
                </label>
                <label style="display:flex;align-items:center;gap:8px;font-weight:500;text-transform:none;letter-spacing:0;cursor:pointer;">
                    <input type="checkbox" name="display_on_invoice" <?= ($editRec['display_on_invoice'] ?? 1) ? 'checked' : '' ?>>
                    Show on Invoice
                </label>
            </div>
        </div>

        <div style="margin-top:16px;display:flex;gap:10px;">
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
            <a href="bank_accounts.php?company_id=<?= $company_id ?>" class="btn btn-secondary">Cancel</a>
        </div>
        </form>
    </div>
</div>
<?php endif; ?>

<div class="panel">
    <div class="panel-header">
        <span class="panel-title">
            <?php if ($companyRec): ?>
            Bank Accounts — <?= htmlspecialchars($companyRec['company_name']) ?>
            <?php else: ?>
            All Bank Accounts
            <?php endif; ?>
        </span>
    </div>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Bank Name</th>
                    <th>Account No</th>
                    <th>IFSC</th>
                    <th>Branch</th>
                    <th>Type</th>
                    <th>UPI ID</th>
                    <th style="text-align:center;">Primary</th>
                    <th style="text-align:center;">On Invoice</th>
                    <th style="text-align:center;">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if (!$banks || $banks->num_rows === 0): ?>
                <tr>
                    <td colspan="9" style="text-align:center;padding:30px;color:var(--text-muted);">
                        No bank accounts added yet.
                    </td>
                </tr>
            <?php else: ?>
                <?php while ($b = $banks->fetch_assoc()): ?>
                <tr>
                    <td>
                        <strong><?= htmlspecialchars($b['bank_name']) ?></strong>
                        <?php if ($b['account_holder']): ?>
                        <br><small><?= htmlspecialchars($b['account_holder']) ?></small>
                        <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($b['account_no']) ?></td>
                    <td><?= htmlspecialchars($b['ifsc']) ?></td>
                    <td><?= htmlspecialchars($b['branch']) ?></td>
                    <td><?= htmlspecialchars($b['account_type']) ?></td>
                    <td><?= htmlspecialchars($b['upi_id'] ?? '') ?></td>
                    <td style="text-align:center;">
                        <?= $b['is_primary']
                            ? '<span class="badge badge-success">Yes</span>'
                            : '—' ?>
                    </td>
                    <td style="text-align:center;">
                        <?= $b['display_on_invoice']
                            ? '<span class="badge badge-success">Yes</span>'
                            : '<span class="badge badge-gray">No</span>' ?>
                    </td>
                    <td>
                        <div class="action-links" style="justify-content:center;">
                            <a href="?action=edit&id=<?= $b['id'] ?>&company_id=<?= $b['company_id'] ?>"
                               class="action-btn edit" title="Edit">
                                <i class="fas fa-edit"></i>
                            </a>
                            <a href="?action=delete&id=<?= $b['id'] ?>&company_id=<?= $b['company_id'] ?>"
                               class="action-btn delete" title="Delete"
                               onclick="return confirm('Delete this bank account?')">
                                <i class="fas fa-trash-alt"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php if ($action === 'add' || $action === 'edit'): ?>
<script>
(function() {
    var ifscEl   = document.getElementById('ifscInput');
    var bankEl   = document.getElementById('bankNameInput');
    var branchEl = document.getElementById('branchInput');
    var spinner  = document.getElementById('ifscSpinner');
    var errEl    = document.getElementById('ifscError');
    if (!ifscEl) return;

    var timer = null;
    ifscEl.addEventListener('input', function() {
        clearTimeout(timer);
        var val = this.value.replace(/\s/g,'').toUpperCase();
        this.value = val;
        errEl.style.display = 'none';
        if (val.length !== 11) return;
        spinner.style.display = 'inline';
        timer = setTimeout(function() {
            fetch('https://ifsc.razorpay.com/' + encodeURIComponent(val))
                .then(function(r) {
                    spinner.style.display = 'none';
                    if (!r.ok) throw new Error('not found');
                    return r.json();
                })
                .then(function(d) {
                    if (d.BANK  && !bankEl.value)   bankEl.value   = d.BANK;
                    if (d.BRANCH && !branchEl.value) branchEl.value = d.BRANCH;
                    if (d.BANK)   bankEl.value   = d.BANK;
                    if (d.BRANCH) branchEl.value = d.BRANCH + (d.CITY ? ', ' + d.CITY : '');
                })
                .catch(function() {
                    spinner.style.display = 'none';
                    errEl.style.display   = 'inline';
                });
        }, 600);
    });
})();
</script>
<?php endif; ?>

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