<?php
session_start();
// error_reporting(E_ALL);
// ini_set('display_errors', 1);

include 'branch_connection.php';

$currentPage = $_GET['page'] ?? 1;

// --------------------
// FORM SUBMIT
// --------------------
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $bank_name        = strtoupper(trim($_POST['bank_name']));
    $branch_name      = strtoupper(trim($_POST['branch_name']));
    $branch_type      = $_POST['branch_type'] ?? '';
    $address          = trim($_POST['address']);
    $account_no       = trim($_POST['account_no']);
    $ifsc             = strtoupper(trim($_POST['ifsc']));
    $opening_balance  = trim($_POST['opening_balance']);
    $upi_id           = trim($_POST['upi_id']);
    $account_type     = trim($_POST['account_type']);
    $status           = trim($_POST['status']);
    $edit_id          = intval($_POST['edit_id']);

    $swal_msg = '';
    $swal_icon = 'success';

    // --------------------
    // CHECK ACCOUNT NO UNIQUE
    // --------------------
    $checkQuery = ($edit_id > 0) 
        ? "SELECT id FROM banks WHERE account_no=? AND id!=?" 
        : "SELECT id FROM banks WHERE account_no=?";

    $checkStmt = $conn->prepare($checkQuery);

    if ($edit_id > 0) {
        $checkStmt->bind_param("si", $account_no, $edit_id);
    } else {
        $checkStmt->bind_param("s", $account_no);
    }

    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();

    if ($checkResult->num_rows > 0) {
        $swal_msg = "Account Number already exists!";
        $swal_icon = "error";
    } else {

        // --------------------
        // UPDATE
        // --------------------
        if ($edit_id > 0) {
            $stmt = $conn->prepare("
                UPDATE banks 
                SET bank_name=?, branch_name=?, branch_type=?, address=?, 
                    account_no=?, ifsc=?, opening_balance=?, upi_id=?, account_type=?, status=? 
                WHERE id=?
            ");
            $stmt->bind_param(
                "ssssssssssi",
                $bank_name,
                $branch_name,
                $branch_type,
                $address,
                $account_no,
                $ifsc,
                $opening_balance,
                $upi_id,
                $account_type,
                $status,
                $edit_id
            );
            $stmt->execute();
            $stmt->close();

            $swal_msg = "Bank updated successfully.";
            $swal_icon = "success";
        } 
        // --------------------
        // INSERT
        // --------------------
        else {
            $stmt = $conn->prepare("
                INSERT INTO banks
                (bank_name, branch_name, branch_type, address, account_no, ifsc, opening_balance, upi_id, account_type, status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->bind_param(
                "ssssssssss",
                $bank_name,
                $branch_name,
                $branch_type,
                $address,
                $account_no,
                $ifsc,
                $opening_balance,
                $upi_id,
                $account_type,
                $status
            );
            $stmt->execute();
            $stmt->close();

            $swal_msg = "New bank added successfully.";
            $swal_icon = "success";
        }
    }

    $checkStmt->close();
    $_SESSION['swal_msg'] = $swal_msg;
    $_SESSION['swal_icon'] = $swal_icon;
    header("Location: add-bank.php?page=$currentPage");
    exit;
}

// ----------------------------
// DELETE BANK
// ----------------------------
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    $stmt = $conn->prepare("DELETE FROM banks WHERE id=?");
    $stmt->bind_param("i", $delete_id);
    $stmt->execute();
    $stmt->close();

    $_SESSION['swal_msg'] = "Bank deleted successfully!";
    $_SESSION['swal_icon'] = "success";
    header("Location: add-bank.php?page=$currentPage");
    exit;
}

// ----------------------------
// FETCH DATA FOR EDIT
// ----------------------------
$edit_id = $_GET['edit_id'] ?? 0;
$edit_row = null;

if ($edit_id > 0) {
    $q = $conn->prepare("SELECT * FROM banks WHERE id=?");
    $q->bind_param("i", $edit_id);
    $q->execute();
    $edit_row = $q->get_result()->fetch_assoc();
    $q->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
   <title>Leads Programers International</title>
   <meta charset="utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="shortcut icon" type="image/png" href="assets/images/favicon.png">
   <link href="assets/vendor/bootstrap-select/dist/css/bootstrap-select.min.css" rel="stylesheet">
   <link href="assets/vendor/bootstrap-datepicker-master/css/bootstrap-datepicker.min.css" rel="stylesheet">
   <link href="assets/vendor/owl-carousel/owl.carousel.css" rel="stylesheet">
   <link href="assets/css/jquery.localizationTool.css" rel="stylesheet">
   <link class="main-css" href="assets/css/style.css" rel="stylesheet">
   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
   <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>
<div id="main-wrapper">
   <div class="nav-header">
      <a href="index.html" class="brand-logo"><img src="assets/images/logo-02.svg" alt=""></a>
      <div class="nav-control"><div class="hamburger"><span class="line"></span><span class="line"></span><span class="line"></span></div></div>
   </div>
   <div class="header">
      <div class="header-content">
         <nav class="navbar navbar-expand">
            <div class="collapse navbar-collapse justify-content-between">
               <div class="header-left"><div class="dashboard_bar">Add Bank</div></div>
               <ul class="navbar-nav header-right">
                  <li class="nav-item dropdown notification_dropdown">
                     <a class="nav-link bell dlab-theme-mode p-0" href="javascript:void(0);"><i id="icon-light" class="fas fa-sun"></i><i id="icon-dark" class="fas fa-moon"></i></a>
                  </li>
                  <?php include "logout.php"; ?>
               </ul>
            </div>
         </nav>
      </div>
   </div>
   <?php include "header.php"; ?>
   <div class="content-body">
      <div class="container-fluid">
         <div class="row">
            <div class="col-xl-12">
               <div class="row">
                  <div class="col-xl-4">
                     <div class="card">
                        <div class="card-body">
                           <div class="basic-form">
                              <form method="POST" action="">
                                 <input type="hidden" name="edit_id" value="<?= $edit_row['id'] ?? 0 ?>">
                                 <div class="mb-3"><input type="text" name="bank_name" class="form-control" placeholder="Bank Name" value="<?= htmlspecialchars($edit_row['bank_name'] ?? '') ?>" required></div>
                                 <div class="mb-3"><input type="text" name="branch_name" class="form-control" placeholder="Branch Name" value="<?= htmlspecialchars($edit_row['branch_name'] ?? '') ?>" required></div>
                                 <div class="mb-3"><textarea name="address" class="form-control" placeholder="Bank Address"><?= htmlspecialchars($edit_row['address'] ?? '') ?></textarea></div>
                                 <div class="mb-3"><input type="text" name="account_no" class="form-control" placeholder="Account No" value="<?= htmlspecialchars($edit_row['account_no'] ?? '') ?>" required></div>
                                 <div class="mb-3"><input type="text" name="ifsc" class="form-control" placeholder="IFSC Code" value="<?= htmlspecialchars($edit_row['ifsc'] ?? '') ?>" required></div>
                                 <div class="mb-3"><input type="text" name="opening_balance" class="form-control" placeholder="Opening Balance" value="<?= htmlspecialchars($edit_row['opening_balance'] ?? '') ?>"></div>
                                 <div class="mb-3"><input type="text" name="upi_id" class="form-control" placeholder="UPI ID" value="<?= htmlspecialchars($edit_row['upi_id'] ?? '') ?>"></div>
                                 <div class="mb-3">
                                    <select name="account_type" class="default-select form-control wide" required>
                                       <option selected disabled>Account Type</option>
                                       <option <?= ($edit_row['account_type'] ?? '')=='Primary'?'selected':'' ?>>Primary</option>
                                       <option <?= ($edit_row['account_type'] ?? '')=='Secondary'?'selected':'' ?>>Secondary</option>
                                    </select>
                                 </div>
                                 <div class="mb-3">
                                    <select name="status" class="default-select form-control wide" required>
                                       <option selected disabled>Status</option>
                                       <option <?= ($edit_row['status'] ?? '')=='Enable'?'selected':'' ?>>Enable</option>
                                       <option <?= ($edit_row['status'] ?? '')=='Disable'?'selected':'' ?>>Disable</option>
                                    </select>
                                 </div>
                                 <button type="submit" class="btn btn-primary w-100"><?= $edit_row ? 'Update' : 'Submit' ?></button>
                              </form>
                           </div>
                        </div>
                     </div>
                  </div>
                  <div class="col-xl-8">
                     <div class="table-responsive">
                        <table class="table table-hover table-responsive-sm">
                           <thead>
                              <tr>
                                 <th>Bank Name</th>
                                 <th>Branch</th>
                                 <th>Address</th>
                                 <th>Account No.</th>
                                 <th>UPI ID</th>
                                 <th>IFSC Code</th>
                                 <th>O.Balance</th>
                                 <th>Type</th>
                                 <th style="text-align: left!important;">Action</th>
                              </tr>
                           </thead>
                           <tbody>
                              <?php 
                              $query = "SELECT * FROM banks ORDER BY id DESC";
                              $resultList = mysqli_query($conn, $query);
                              if ($resultList->num_rows > 0): ?>
                                 <?php while ($row = $resultList->fetch_assoc()): ?>
                                 <tr>
                                    <td><?= htmlspecialchars($row['bank_name']) ?></td>
                                    <td><?= htmlspecialchars($row['branch_name']) ?></td>
                                    <td><?= htmlspecialchars($row['address']) ?></td>
                                    <td><?= htmlspecialchars($row['account_no']) ?></td>
                                    <td><?= htmlspecialchars($row['upi_id']) ?></td>
                                    <td><?= htmlspecialchars($row['ifsc']) ?></td>
                                    <td><?= htmlspecialchars($row['opening_balance']) ?></td>
                                    <td><?= htmlspecialchars($row['account_type']) ?></td>
                                    <td style="text-align:center;">
                                       <span class="d-flex" style="gap:2px;width: 100%;text-align:center;">
                                          <a href="add-bank.php?edit_id=<?= $row['id'] ?>&page=<?= $currentPage ?>" class="text-warning me-3"><i class="fa fa-edit"></i></a>
                                          <a href="#" class="text-danger delete-bank" data-id="<?= $row['id'] ?>"><i class="fa fa-trash"></i></a>
                                       </span>
                                    </td>
                                 </tr>
                                 <?php endwhile; ?>
                              <?php else: ?>
                                 <tr><td colspan="10" class="text-center">No records found.</td></tr>
                              <?php endif; ?>
                           </tbody>
                        </table>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
   <?php include "footer.php"; ?>
</div>

<script src="assets/vendor/global/global.min.js"></script>
<script src="assets/vendor/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
<script src="assets/vendor/bootstrap-datepicker-master/js/bootstrap-datepicker.min.js"></script>
<script src="assets/vendor/chartjs/chart.bundle.min.js"></script>
<script src="assets/vendor/peity/jquery.peity.min.js"></script>
<script src="assets/js/custom.min.js"></script>
<script src="assets/js/dlabnav-init.js"></script>
<script src="assets/js/demo.js"></script>

<script>
document.querySelectorAll('.delete-bank').forEach(function(btn) {
    btn.addEventListener('click', function(e) {
        e.preventDefault();
        let bankId = this.getAttribute('data-id');

        Swal.fire({
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = `add-bank.php?delete_id=${bankId}&page=<?= $currentPage ?>`;
            }
        });
    });
});

// --------------------
// SweetAlert after actions
// --------------------
<?php if(isset($_SESSION['swal_msg'])): ?>
Swal.fire({
    icon: '<?= $_SESSION['swal_icon'] ?? "info" ?>',
    title: '<?= $_SESSION['swal_msg'] ?>',
    showConfirmButton: false,
    timer: 2000
});
<?php 
unset($_SESSION['swal_msg'], $_SESSION['swal_icon']);
endif; 
?>
</script>
</body>
</html>
<?php
$conn->close();
?>
