<?php

ob_start();

error_reporting(E_ALL);
ini_set('display_errors',1);

if(session_status()===PHP_SESSION_NONE){
    session_start();
}

if(
!isset($_SESSION['role']) ||
$_SESSION['role']!="admin"
){
    die("Access Denied");
}

include("../../../config/db.php");
include("../../../templates/header.php");
include("../../../templates/sidebar.php");


/* ======================================================
   CURRENT PAGE
====================================================== */

$currentPage =
basename($_SERVER['PHP_SELF']);


/* ======================================================
   AJAX UPDATE
====================================================== */

if(
$_SERVER['REQUEST_METHOD']==="POST"
&&
isset($_POST['ajax_update'])
){

    ob_clean();

    header("Content-Type: application/json");

    $id =
    intval($_POST['id']);

    $holder =
    trim($_POST['holder']);

    $bank =
    trim($_POST['bank']);

    $acc =
    trim($_POST['acc']);

    $email =
    $_SESSION['email'] ?? 'admin';


    /* ======================================================
       ACCOUNT HOLDER VALIDATION
    ====================================================== */

    if(
    !preg_match(
    "/^[a-zA-Z\s.@'-]{3,50}$/",
    $holder
    )
    ){

        echo json_encode([
            "status"=>"error",
            "message"=>"Account holder cannot contain numbers"
        ]);

        exit;
    }


    /* ======================================================
       BANK VALIDATION
    ====================================================== */

    if(empty($bank)){

        echo json_encode([
            "status"=>"error",
            "message"=>"Bank is required"
        ]);

        exit;
    }


    /* ======================================================
       ACCOUNT NUMBER VALIDATION
    ====================================================== */

    if(
    !preg_match(
    "/^[0-9-]{8,20}$/",
    $acc
    )
    ){

        echo json_encode([
            "status"=>"error",
            "message"=>"Account number only allows numbers and dash (-)"
        ]);

        exit;
    }


    /* ======================================================
       ESCAPE
    ====================================================== */

    $holder =
    strtoupper(
    mysqli_real_escape_string(
    $conn,
    $holder
    ));

    $bank =
    mysqli_real_escape_string(
    $conn,
    $bank
    );

    $acc =
    mysqli_real_escape_string(
    $conn,
    $acc
    );


    /* ======================================================
       UPDATE
    ====================================================== */

    $update =
    mysqli_query($conn,"
    
    UPDATE bank_accounts
    SET

        account_holder_name='$holder',
        bank_name='$bank',
        account_number='$acc',
        updated_by='$email',
        updated_at=NOW()

    WHERE id=$id
    
    ");

    if(!$update){

        echo json_encode([
            "status"=>"error",
            "message"=>mysqli_error($conn)
        ]);

        exit;
    }

    echo json_encode([
        "status"=>"success",
        "message"=>"Bank updated successfully"
    ]);

    exit;
}


/* ======================================================
   FETCH DATA
====================================================== */

$q = mysqli_query($conn,"

SELECT

    b.id AS bank_id,
    o.club_name,
    b.account_holder_name,
    b.bank_name,
    b.account_number,
    b.updated_by,
    b.updated_at

FROM bank_accounts b

LEFT JOIN users u
ON u.id=b.user_id

LEFT JOIN organizers o
ON o.user_id=u.id

ORDER BY b.updated_at DESC

");

?>

<link
rel="stylesheet"
href="/SEAT/assets/css/admin/edit_bank.css"
>

<div class="content">




    <!-- ======================================================
         TAB BAR
    ====================================================== -->

    <div class="tabBar">

        <a
        href="manage_organizer.php"
        class="<?= $currentPage=="manage_organizer.php"
        ? "active"
        : "" ?>"
        >
        Pending Organizers
        </a>

        <a
        href="edit_bank.php"
        class="<?= $currentPage=="edit_bank.php"
        ? "active"
        : "" ?>"
        >
        Organizer Bank
        </a>

    </div>


    <!-- ======================================================
         CARD
    ====================================================== -->

    <div class="bankCard">

        <!-- ======================================================
             CARD HEADER
        ====================================================== -->

        <div class="cardHeader">

            <div>

                <h3 class="cardTitle">
                    Organizer Bank Accounts
                </h3>

                <p class="cardSub">
                    Edit and maintain organizer banking details.
                </p>

            </div>

            <div class="searchBox">

                <span class="searchIcon">
                    ⌕
                </span>

                <input
                type="text"
                id="searchInput"
                class="inputSearch"
                placeholder="Search organizer..."
                >

            </div>

        </div>


        <!-- ======================================================
             TABLE
        ====================================================== -->

        <div class="tableWrapper">

            <table
            class="table"
            id="bankTable"
            >

                <thead>

                    <tr>

                        <th>Club</th>
                        <th>Account</th>
                        <th>Updated</th>
                        <th>Action</th>

                    </tr>

                </thead>

                <tbody id="tableBody">

                <?php

                while(
                $r=mysqli_fetch_assoc($q)
                ){

                    $acc =
                    $r['account_number'] ?? '';

                    $masked =
                    $acc
                    ? str_repeat(
                        "*",
                        max(strlen($acc)-4,0)
                    )
                    . substr($acc,-4)
                    : 'N/A';

                ?>

                <tr>

                    <td>

                        <?= htmlspecialchars(
                            $r['club_name']
                        ) ?>

                    </td>

                    <td class="acc">

                        <?= $masked ?>

                    </td>

                    <td>

                        <?php if($r['updated_at']){ ?>

                            <?= date(
                            "d M Y H:i",
                            strtotime(
                            $r['updated_at']
                            )) ?>

                            <br>

                            <small>

                                by
                                <?= htmlspecialchars(
                                $r['updated_by']
                                ) ?>

                            </small>

                        <?php } else { ?>

                            Never

                        <?php } ?>

                    </td>

                    <td>

                        <button
                        class="btn btnBlue"
                        onclick="openModal(
                        '<?= $r['bank_id'] ?>',
                        '<?= htmlspecialchars(
                        $r['account_holder_name'],
                        ENT_QUOTES
                        ) ?>',
                        '<?= htmlspecialchars(
                        $r['bank_name'],
                        ENT_QUOTES
                        ) ?>',
                        '<?= htmlspecialchars(
                        $acc,
                        ENT_QUOTES
                        ) ?>'
                        )"
                        >

                        <span class="editIcon">
                            ✏
                        </span>

                        Edit

                        </button>

                    </td>

                </tr>

                <?php } ?>

                </tbody>

            </table>

        </div>


        <!-- ======================================================
             PAGINATION
        ====================================================== -->

        <div class="paginationWrap">

            <button
            class="pageBtn"
            id="prevPage"
            >
            Previous
            </button>

            <div id="paginationNumbers"></div>

            <button
            class="pageBtn"
            id="nextPage"
            >
            Next
            </button>

        </div>

    </div>

</div>



<!-- ======================================================
   MODAL
====================================================== -->

<div id="bankModal" class="modal">

    <div class="modalBox">

        <h3>
            Edit Bank
        </h3>

        <input
        type="hidden"
        id="m_id"
        >


        <!-- ACCOUNT HOLDER -->

        <label>
            Account Holder
        </label>

        <input
        type="text"
        id="m_holder"
        maxlength="50"
        oninput="
        this.value=
        this.value.replace(
        /[^a-zA-Z\s.@'-]/g,
        ''
        )
        "
        >


        <!-- BANK -->

        <label>
            Bank Name
        </label>

        <select id="m_bank">

            <option value="">
                Select Bank
            </option>

            <option>Maybank</option>
            <option>CIMB Bank</option>
            <option>Public Bank</option>
            <option>RHB Bank</option>
            <option>Hong Leong Bank</option>
            <option>AmBank</option>

        </select>


        <!-- ACCOUNT NUMBER -->

        <label>
            Account Number
        </label>

        <input
        type="text"
        id="m_acc"
        maxlength="20"
        oninput="
        this.value=
        this.value.replace(
        /[^0-9-]/g,
        ''
        )
        "
        >


        <!-- BUTTONS -->

        <div class="modalActions">

            <button
            class="btn btnGray"
            onclick="closeModal()"
            >
            Cancel
            </button>

            <button
            class="btn btnGreen"
            onclick="saveBank()"
            >
            Save
            </button>

        </div>

    </div>

</div>



<!-- ======================================================
   TOAST
====================================================== -->

<div id="toastContainer"></div>



<script>

/* ======================================================
   ELEMENTS
====================================================== */

const modal =
document.getElementById("bankModal");

const m_id =
document.getElementById("m_id");

const m_holder =
document.getElementById("m_holder");

const m_bank =
document.getElementById("m_bank");

const m_acc =
document.getElementById("m_acc");


/* ======================================================
   LIVE VALIDATION
====================================================== */

m_holder.addEventListener(
"input",
function(){

    m_holder.value =
    m_holder.value.replace(
    /[^a-zA-Z\s.@'-]/g,
    ''
    );

}
);

m_acc.addEventListener(
"input",
function(){

    m_acc.value =
    m_acc.value.replace(
    /[^0-9-]/g,
    ''
    );

}
);


/* ======================================================
   OPEN MODAL
====================================================== */

function openModal(
id,
holder,
bank,
acc
){

    modal.style.display="flex";

    m_id.value=id;

    m_holder.value=holder;

    m_bank.value=bank;

    m_acc.value=acc;
}


/* ======================================================
   CLOSE MODAL
====================================================== */

function closeModal(){

    modal.style.display="none";
}


/* ======================================================
   TOAST
====================================================== */

function toast(
msg,
type="success"
){

    let c =
    document.getElementById(
    "toastContainer"
    );

    let t =
    document.createElement("div");

    t.className =
    "toast " + type;

    t.innerHTML = `
        <div class="toastIcon">
            ${type==="success"
            ? "✔"
            : "✖"}
        </div>

        <div>${msg}</div>
    `;

    c.appendChild(t);

    setTimeout(()=>{
        t.classList.add("show");
    },50);

    setTimeout(()=>{

        t.classList.remove("show");

        setTimeout(()=>{
            t.remove();
        },300);

    },3000);
}


/* ======================================================
   SAVE
====================================================== */

async function saveBank(){

    const holder =
    m_holder.value.trim();

    const acc =
    m_acc.value.trim();

    if(
    !/^[a-zA-Z\s.@'-]{3,50}$/
    .test(holder)
    ){

        toast(
        "Invalid account holder name",
        "error"
        );

        return;
    }

    if(
    !/^[0-9-]{8,20}$/
    .test(acc)
    ){

        toast(
        "Account number only allows numbers and dash (-)",
        "error"
        );

        return;
    }

    let form =
    new FormData();

    form.append(
    "ajax_update",
    "1"
    );

    form.append(
    "id",
    m_id.value
    );

    form.append(
    "holder",
    holder
    );

    form.append(
    "bank",
    m_bank.value
    );

    form.append(
    "acc",
    acc
    );

    try{

        const response =
        await fetch(
        "edit_bank.php",
        {
            method:"POST",
            body:form
        }
        );

        const d =
        await response.json();

        if(
        d.status==="success"
        ){

            toast(
            d.message,
            "success"
            );

            closeModal();

            setTimeout(()=>{
                location.reload();
            },700);

        }else{

            toast(
            d.message,
            "error"
            );
        }

    }catch(err){

        console.error(err);

        toast(
        "Server error",
        "error"
        );
    }
}


/* ======================================================
   SEARCH + PAGINATION
====================================================== */

const rowsPerPage = 5;

let currentPage = 1;

function getFilteredRows(){

    const val =
    document
    .getElementById(
    "searchInput"
    )
    .value
    .toLowerCase();

    return [
    ...document.querySelectorAll(
    "#tableBody tr"
    )]

    .filter(row =>

        row.innerText
        .toLowerCase()
        .includes(val)

    );
}

function renderTable(){

    const rows =
    getFilteredRows();

    const totalPages =
    Math.ceil(
    rows.length /
    rowsPerPage
    ) || 1;

    if(
    currentPage > totalPages
    ){
        currentPage =
        totalPages;
    }

    document
    .querySelectorAll(
    "#tableBody tr"
    )
    .forEach(row =>

        row.style.display="none"

    );

    const start =
    (currentPage - 1)
    * rowsPerPage;

    const end =
    start + rowsPerPage;

    rows
    .slice(start,end)

    .forEach(row => {

        row.style.display = "";

    });

    renderPagination(totalPages);
}

function renderPagination(totalPages){

    const container =
    document.getElementById(
    "paginationNumbers"
    );

    container.innerHTML = "";

    for(
    let i=1;
    i<=totalPages;
    i++
    ){

        const btn =
        document.createElement(
        "button"
        );

        btn.className =
        "pageNumber " +
        (i===currentPage
        ? "active"
        : "");

        btn.innerText = i;

        btn.onclick = () => {

            currentPage = i;

            renderTable();
        };

        container.appendChild(btn);
    }
}

document
.getElementById(
"searchInput"
)

.addEventListener(
"input",
() => {

    currentPage = 1;

    renderTable();

}
);

document
.getElementById(
"prevPage"
)

.addEventListener(
"click",
() => {

    if(currentPage > 1){

        currentPage--;

        renderTable();
    }

}
);

document
.getElementById(
"nextPage"
)

.addEventListener(
"click",
() => {

    const totalPages =
    Math.ceil(

        getFilteredRows().length /
        rowsPerPage

    );

    if(
    currentPage < totalPages
    ){

        currentPage++;

        renderTable();
    }

}
);

renderTable();

</script>