<?php
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
require("includes/config.php");
require("includes/function.php");
require("includes/check_permission.php");

$formname  = 'Cash';
$maindb    = 'accmast';
$printfile = 'cash_print.php';
$file      = 'cash.php';
$keyfld    = 'accode';
$keycond   = " AND `grpcode`='002'";
$mgrpcode  = '002';

$zdb      = $_SESSION["zdbyear_" . $dbname];
$compcd   = $_SESSION["comp_"    . $dbname];
$usertype = $_SESSION["usertype_" . $dbname];

mysqli_select_db($conn, $zdb);

include("includes/vouchno_generate.php");
include("includes/prev_next.php");

// ── POST: Insert / Update ────────────────────────────────────────────────────
if (isset($_POST["submit"])) {
    $name    = mysqli_real_escape_string($conn, trim($_POST["name"]));
    $openbal = mysqli_real_escape_string($conn, $_POST["openbal"]);
    $opendc  = mysqli_real_escape_string($conn, $_POST["opendc"]);

    $a = 1;

    if ($name == '') {
        $a = 0;
        browse("Name Cannot Be Empty");
        header("refresh:1; url=$file?mode=last");
    }

    if ($a == 1) {
        $chkdup = mysqli_query($conn, "SELECT `accode` FROM `$maindb` WHERE `name`='$name' AND `accode`!='$qvouch'") or die(mysqli_error($conn));
        if (mysqli_num_rows($chkdup) > 0) {
            $a = 0;
            browse("Account With This Name Already Exists");
            header("refresh:1; url=$file?mode=last");
        }
    }

    if ($a == 1) {
        $audituser = mysqli_real_escape_string($conn, audituser());

        if ($addflag == 1) {
            mysqli_query($conn, "INSERT INTO `$maindb`
                (`accode`,`grpcode`,`name`,`openbal`,`dc`,`adduser`,`adddate`,`addtime`)
                VALUES
                ('$qvouch','$mgrpcode','$name','$openbal','$opendc','$audituser',CURDATE(),CURTIME())")
            or die(mysqli_error($conn));
            insmess();
            header("refresh:1; url=$file?$keyfld=$qvouch&mode=edit");
        } else {
            mysqli_query($conn, "UPDATE `$maindb` SET
                `name`='$name', `openbal`='$openbal', `dc`='$opendc',
                `edituser`='$audituser', `editdate`=CURDATE(), `edittime`=CURTIME()
                WHERE `accode`='$qvouch' AND `grpcode`='$mgrpcode'")
            or die(mysqli_error($conn));
            updmess();
            header("refresh:1; url=$file?$keyfld=$qvouch&mode=edit");
        }
    }
}

// ── Fetch record ─────────────────────────────────────────────────────────────
$get = [];
if ($addflag != 1 && $qvouch > 0) {
    $result = mysqli_query($conn, "SELECT * FROM `$maindb` WHERE `$keyfld`='$qvouch' AND `grpcode`='$mgrpcode'") or die(mysqli_error($conn));
    $get    = mysqli_fetch_array($result);
    if (!$get) $get = [];
}

// ── DELETE ───────────────────────────────────────────────────────────────────
if (isset($_GET["delete"])) {
    if ($usertype != 1) { header("refresh:1; url=$file?mode=last"); exit; } // admin-only delete guard
    $chkdel = mysqli_query($conn, "SELECT `accode` FROM `actran` WHERE `accode`='$qvouch'") or die(mysqli_error($conn));
    if (mysqli_num_rows($chkdel) > 0) {
        browse("Cash Exists in Transactions. Cannot Delete.");
    } else {
        mysqli_query($conn, "DELETE FROM `$maindb` WHERE `$keyfld`='$qvouch' AND `grpcode`='$mgrpcode'") or die(mysqli_error($conn));
        delmess();
    }
    header("refresh:1; url=$file?mode=last");
    exit;
}

// Helper: get value safely
function fv($get, $key, $default = '') {
    return isset($get[$key]) ? htmlspecialchars($get[$key]) : $default;
}

include("includes/linkshead.php");
?>
<style>
    body { background:#f0f2f5; margin:0; padding:10px 14px; }

    .sim-card {
        background:#fff;
        border-radius:10px;
        box-shadow:0 1px 3px rgba(0,0,0,.08), 0 4px 16px rgba(0,0,0,.06);
        overflow:hidden;
    }

    .sim-card-header {
        background:#fff;
        border-bottom:2px solid #f1f5f9;
        padding:12px 20px;
        display:flex;
        align-items:center;
        justify-content:space-between;
    }
    .sim-card-header h2 {
        font-size:15px;
        font-weight:700;
        color:#1e293b;
        margin:0;
        letter-spacing:.01em;
    }
    .sim-badge {
        font-size:11px;
        background:#f1f5f9;
        color:#64748b;
        border-radius:20px;
        padding:3px 10px;
        font-weight:600;
    }

    .sim-body { padding:20px; }

    /* Form rows */
    .fr { display:flex; align-items:center; margin-bottom:9px; gap:0; }
    .fr-2 { display:grid; grid-template-columns:1fr 1fr; gap:0 16px; margin-bottom:9px; }

    .fl { /* field wrapper */
        display:flex;
        align-items:center;
        flex:1;
    }

    .lbl {
        font-size:12px;
        font-weight:500;
        color:#64748b;
        white-space:nowrap;
        text-align:right;
        padding-right:10px;
        min-width:130px;
        flex-shrink:0;
    }
    .lbl-sm { min-width:90px; }

    .finp {
        flex:1;
        padding:7px 11px;
        background:#f8fafc;
        border:1px solid #e2e8f0;
        border-radius:6px;
        font-size:12.5px;
        color:#1e293b;
        outline:none;
        transition:border-color .15s, background .15s, box-shadow .15s;
        width:100%;
        box-sizing:border-box;
        font-family:inherit;
    }
    .finp:focus {
        background:#fff;
        border-color:#3b82f6;
        box-shadow:0 0 0 3px rgba(59,130,246,.12);
    }
    .finp:disabled {
        background:#f1f5f9;
        color:#94a3b8;
        cursor:not-allowed;
        border-color:#e2e8f0;
    }
    .finp.required-star { border-left:3px solid #3b82f6; }

    /* Button bar */
    .btn-bar {
        display:flex;
        justify-content:center;
        align-items:center;
        gap:8px;
        padding:16px 20px;
        border-top:1px solid #f1f5f9;
        background:#fafafa;
    }
    .abtn {
        width:46px;
        height:46px;
        border-radius:10px;
        border:none;
        cursor:pointer;
        font-size:15px;
        color:#fff;
        display:inline-flex;
        align-items:center;
        justify-content:center;
        text-decoration:none;
        transition:transform .12s, box-shadow .12s, filter .12s;
        position:relative;
    }
    .abtn:hover { transform:translateY(-2px); box-shadow:0 5px 14px rgba(0,0,0,.22); filter:brightness(1.06); }
    .abtn:active { transform:translateY(0); box-shadow:none; filter:brightness(.95); }
    .abtn[disabled] { opacity:.4; pointer-events:none; }

    .abtn-prev   { background:#2563eb; }
    .abtn-next   { background:#38bdf8; }
    .abtn-search { background:#db2777; }
    .abtn-print  { background:#7c3aed; }
    .abtn-add    { background:#16a34a; }
    .abtn-edit   { background:#ea580c; }
    .abtn-del    { background:#dc2626; }
    .abtn-exit   { background:#e2e8f0; color:#64748b; }

    /* tooltip on hover */
    .abtn::after {
        content: attr(data-tip);
        position:absolute;
        bottom:calc(100% + 6px);
        left:50%;
        transform:translateX(-50%);
        background:#1e293b;
        color:#fff;
        font-size:10px;
        font-weight:600;
        padding:3px 8px;
        border-radius:4px;
        white-space:nowrap;
        opacity:0;
        pointer-events:none;
        transition:opacity .15s;
    }
    .abtn:hover::after { opacity:1; }

    /* Save/Cancel extended buttons */
    .abtn-save   { width:auto; padding:0 18px; background:#16a34a; gap:6px; font-size:12.5px; font-weight:600; }
    .abtn-cancel { width:auto; padding:0 16px; background:#64748b; gap:6px; font-size:12.5px; font-weight:600; }

    /* Audit info footer */
    .audit-info {
        margin-top:14px;
        padding-top:10px;
        border-top:1px dashed #e2e8f0;
        display:flex;
        flex-wrap:wrap;
        gap:16px;
        font-size:11px;
        color:#94a3b8;
    }
    .audit-info i { margin-right:4px; }
    .audit-info b { color:#64748b; }
</style>

<body>
<form action="" method="POST">
<div class="sim-card">

    <!-- Header -->
    <div class="sim-card-header">
        <h2><i class="fa fa-money-bill-wave" style="color:#3b82f6;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?></h2>
        <span class="sim-badge">Code: <?php echo $qvouch > 0 ? $qvouch : 'New'; ?></span>
    </div>

    <div class="sim-body">

        <!-- Name -->
        <div class="fr">
            <div class="fl">
                <span class="lbl">Name <span style="color:#ef4444;">*</span></span>
                <input type="text" name="name" class="finp form focusfield required-star" required
                    value="<?php echo fv($get,'name'); ?>">
            </div>
        </div>

        <!-- Opening Balance | D/C -->
        <div class="fr-2">
            <div class="fl">
                <span class="lbl">Opening Balance</span>
                <input type="text" name="openbal" class="finp form no-arrows"
                    value="<?php echo fv($get,'openbal','0'); ?>">
            </div>
            <div class="fl">
                <span class="lbl lbl-sm">Dr / Cr</span>
                <select name="opendc" class="finp form" style="max-width:120px;">
                    <option value="D" <?php echo (fv($get,'dc','D') == 'D') ? 'selected' : ''; ?>>Debit (Dr)</option>
                    <option value="C" <?php echo (fv($get,'dc') == 'C') ? 'selected' : ''; ?>>Credit (Cr)</option>
                </select>
            </div>
        </div>

        <!-- Audit Info -->
        <?php if ($qvouch > 0 && (fv($get,'adduser') != '' || fv($get,'edituser') != '')): ?>
        <div class="audit-info">
            <?php if (fv($get,'adduser') != ''): ?>
            <span><i class="fa fa-plus-circle"></i> Added by <b><?php echo fv($get,'adduser'); ?></b> on <?php echo fv($get,'adddate'); ?> <?php echo fv($get,'addtime'); ?></span>
            <?php endif; ?>
            <?php if (fv($get,'edituser') != ''): ?>
            <span><i class="fa fa-pen"></i> Last edited by <b><?php echo fv($get,'edituser'); ?></b> on <?php echo fv($get,'editdate'); ?> <?php echo fv($get,'edittime'); ?></span>
            <?php endif; ?>
        </div>
        <?php endif; ?>

    </div><!-- /sim-body -->

    <!-- Action Button Bar -->
    <div class="btn-bar">

        <!-- Browse buttons (hidden in add mode) -->
        <button id="hprevious" type="button" class="abtn abtn-prev buttonform"
            style="display:<?php echo $pdisabled; ?>;"
            data-tip="Previous"
            onclick="window.location.href='<?php echo $file . '?mode=edit&' . $keyfld . '=' . $prevvouch; ?>'"
            <?php echo $pdisabled1; ?>>
            <i class="fa fa-chevron-left"></i>
        </button>

        <button id="hnext" type="button" class="abtn abtn-next buttonform"
            style="display:<?php echo $ndisabled; ?>;"
            data-tip="Next"
            onclick="window.location.href='<?php echo $file . '?mode=edit&' . $keyfld . '=' . $nextvouch; ?>'"
            <?php echo $ndisabled1; ?>>
            <i class="fa fa-chevron-right"></i>
        </button>

        <button id="hsearch" type="button" class="abtn abtn-search buttonform"
            style="display:<?php echo $searchdisabled; ?>;"
            data-tip="Search"
            onclick="document.getElementById('searchModal').style.display='flex'">
            <i class="fa fa-search"></i>
        </button>

        <button id="hprint" type="button" class="abtn abtn-print buttonform"
            style="display:<?php echo $printdisabled; ?>;"
            data-tip="Print"
            onclick="window.open('<?php echo $printfile . '?' . $keyfld . '=' . $qvouch; ?>','_blank')">
            <i class="fa fa-print"></i>
        </button>

        <button id="hadd" type="button" class="abtn abtn-add buttonform"
            style="display:<?php echo $adddisabled; ?>;"
            data-tip="Add New"
            onclick="window.location.href='<?php echo $file . '?mode=true'; ?>'">
            <i class="fa fa-plus"></i>
        </button>

        <button id="hedit" type="button" class="abtn abtn-edit buttonform"
            style="display:<?php echo $editdisabled; ?>;"
            data-tip="Edit">
            <i class="fa fa-pencil"></i>
        </button>

        <a id="hdelete" class="abtn abtn-del buttonform"
            style="display:<?php echo $deletedisabled; ?>;"
            data-tip="Delete"
            href="javascript:void(0)"
            onclick="confirmDelete('?delete&<?php echo $keyfld . '=' . $qvouch; ?>')">
            <i class="fa fa-trash"></i>
        </a>

        <button id="hexit" type="button" class="abtn abtn-exit buttonform"
            style="display:<?php echo $exitdisabled; ?>;"
            data-tip="Exit"
            onclick="window.location.href='default.php'">
            <i class="fa fa-power-off"></i>
        </button>

        <!-- Save / Cancel (hidden in browse mode) -->
        <button id="ssubmit" type="submit" name="submit"
            value="<?php echo ($addflag == 1) ? 'Save' : 'Update'; ?>"
            class="abtn abtn-save buttonform"
            data-tip="<?php echo ($addflag == 1) ? 'Save' : 'Update'; ?>"
            style="display:<?php echo $savedisabled; ?>;">
            <i class="fa fa-check"></i>
            <?php echo ($addflag == 1) ? 'Save' : 'Update'; ?>
        </button>

        <button id="scancel" type="button"
            class="abtn abtn-cancel buttonform"
            data-tip="Cancel"
            style="display:<?php echo $canceldisabled; ?>;"
            onclick="window.location.href='<?php echo $file . '?mode=last'; ?>'">
            <i class="fa fa-times"></i> Cancel
        </button>

    </div>

</div><!-- /sim-card -->
</form>


<!-- ── Search Modal ─────────────────────────────────────────────────────────── -->
<div id="searchModal"
    style="display:none;position:fixed;inset:0;background:rgba(15,23,42,.5);z-index:9999;
           align-items:flex-start;justify-content:center;padding-top:60px;">
    <div style="background:#fff;border-radius:12px;width:94%;max-width:980px;overflow:hidden;
                box-shadow:0 24px 64px rgba(0,0,0,.3);max-height:85vh;display:flex;flex-direction:column;">

        <!-- Modal header -->
        <div style="padding:14px 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #f1f5f9;">
            <span style="font-size:14px;font-weight:700;color:#1e293b;">
                <i class="fa fa-search" style="color:#db2777;margin-right:8px;"></i>Search <?php echo $formname; ?>
            </span>
            <button type="button"
                style="background:#f1f5f9;border:none;color:#64748b;width:30px;height:30px;border-radius:6px;cursor:pointer;font-size:16px;display:flex;align-items:center;justify-content:center;"
                onclick="document.getElementById('searchModal').style.display='none'">&times;</button>
        </div>

        <!-- Filter row -->
        <div style="padding:12px 18px;border-bottom:1px solid #f1f5f9;display:flex;flex-wrap:wrap;gap:8px;align-items:end;background:#fafbfc;">
            <div>
                <label style="display:block;font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#94a3b8;margin-bottom:4px;">Field</label>
                <select id="srchField" style="padding:7px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:12.5px;outline:none;background:#fff;">
                    <option value="id">ID</option>
                    <option value="name" selected>Name</option>
                    <option value="openbal">Opening Bal.</option>
                </select>
            </div>
            <div>
                <label style="display:block;font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#94a3b8;margin-bottom:4px;">Operator</label>
                <select id="srchOperator" style="padding:7px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:12.5px;outline:none;background:#fff;">
                    <option value="like" selected>Like</option>
                    <option value="=">=</option>
                </select>
            </div>
            <div>
                <label style="display:block;font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#94a3b8;margin-bottom:4px;">Sort By</label>
                <select id="srchSortField" style="padding:7px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:12.5px;outline:none;background:#fff;">
                    <option value="id">ID</option>
                    <option value="name" selected>Name</option>
                    <option value="openbal">Opening Bal.</option>
                </select>
            </div>
            <div>
                <label style="display:block;font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#94a3b8;margin-bottom:4px;">Order</label>
                <select id="srchSortOrder" style="padding:7px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:12.5px;outline:none;background:#fff;">
                    <option value="asc" selected>Asc</option>
                    <option value="desc">Desc</option>
                </select>
            </div>
            <div style="flex:1;min-width:160px;">
                <label style="display:block;font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#94a3b8;margin-bottom:4px;">Search</label>
                <input type="text" id="srchInput"
                    style="width:100%;padding:7px 11px;border:1px solid #e2e8f0;border-radius:6px;font-size:12.5px;outline:none;background:#fff;box-sizing:border-box;">
            </div>
            <div>
                <button type="button" id="srchGoBtn"
                    style="padding:8px 18px;border-radius:6px;border:none;background:#2563eb;color:#fff;font-size:12.5px;font-weight:600;cursor:pointer;">
                    <i class="fa fa-search"></i> Search
                </button>
            </div>
        </div>

        <!-- Table -->
        <div style="overflow:auto;flex:1;">
            <table style="width:100%;border-collapse:collapse;font-size:12px;">
                <thead>
                    <tr style="position:sticky;top:0;background:#f8fafc;">
                        <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">ID</th>
                        <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">Name</th>
                        <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">Opening Bal.</th>
                        <th style="padding:9px 14px;text-align:left;border-bottom:2px solid #e2e8f0;font-weight:600;color:#374151;font-size:11.5px;">CR/DR</th>
                    </tr>
                </thead>
                <tbody id="srchBody"></tbody>
            </table>
        </div>

        <!-- Pagination footer -->
        <div style="display:flex;border-top:1px solid #f1f5f9;">
            <button type="button" id="srchPrevBtn"
                style="flex:1;padding:10px;border:none;background:#f8fafc;color:#374151;font-size:12.5px;font-weight:600;cursor:pointer;border-right:1px solid #f1f5f9;">
                <i class="fa fa-chevron-left"></i> Previous
            </button>
            <span id="srchPageInfo" style="padding:10px 16px;font-size:12px;color:#64748b;white-space:nowrap;align-self:center;"></span>
            <button type="button" id="srchNextBtn"
                style="flex:1;padding:10px;border:none;background:#f8fafc;color:#374151;font-size:12.5px;font-weight:600;cursor:pointer;border-left:1px solid #f1f5f9;">
                Next <i class="fa fa-chevron-right"></i>
            </button>
        </div>

    </div>
</div>

<script>
// ── Search modal (AJAX) ──────────────────────────────────────────────────────
var srchPage = 1;
var srchPages = 1;

function srchLoad(page) {
    srchPage = page;
    $.post('includes/bankcash_search.php', {
        grpcode:   '<?php echo $mgrpcode; ?>',
        file:      '<?php echo $file; ?>',
        keyfld:    '<?php echo $keyfld; ?>',
        field:     $('#srchField').val(),
        operator:  $('#srchOperator').val(),
        sortfield: $('#srchSortField').val(),
        sortorder: $('#srchSortOrder').val(),
        search:    $('#srchInput').val(),
        page:      page
    }, function (data) {
        $('#srchBody').html(data.rows);
        srchPage  = data.page;
        srchPages = data.pages;
        $('#srchPageInfo').text('Page ' + srchPage + ' of ' + srchPages + ' (' + data.total + ' records)');
        $('#srchPrevBtn').prop('disabled', srchPage <= 1).css('opacity', srchPage <= 1 ? .5 : 1);
        $('#srchNextBtn').prop('disabled', srchPage >= srchPages).css('opacity', srchPage >= srchPages ? .5 : 1);
    }, 'json');
}

$('#srchGoBtn').on('click', function () { srchLoad(1); });
$('#srchInput').on('keyup', function (e) { if (e.key === 'Enter') srchLoad(1); });
$('#srchPrevBtn').on('click', function () { if (srchPage > 1) srchLoad(srchPage - 1); });
$('#srchNextBtn').on('click', function () { if (srchPage < srchPages) srchLoad(srchPage + 1); });

// Close on backdrop
document.getElementById('searchModal').addEventListener('click', function (e) {
    if (e.target === this) this.style.display = 'none';
});
// Load + focus search input when modal opens
document.getElementById('hsearch') && document.getElementById('hsearch').addEventListener('click', function () {
    srchLoad(1);
    setTimeout(function () { document.getElementById('srchInput').focus(); }, 60);
});
</script>

<?php include("includes/linksfoot.php"); ?>
</body>
</html>
