<?php
/**
 * cash_entry.php (root page) — Dark Theme
 * Upload: /home/jewellersbd/public_html/erp.jewellersbd.com/cash_entry.php
 */
require_once __DIR__ . '/config/session.php';
require_once __DIR__ . '/config/db.php';
if (session_status() === PHP_SESSION_NONE) session_start();
if (empty($_SESSION['user_id'])) { header('Location: ui/login.html'); exit; }

$accounts = $pdo->query("SELECT id, account_name, account_name_bn, current_balance FROM cash_accounts WHERE is_active=1 AND deleted_at IS NULL ORDER BY sort_order,id")->fetchAll(PDO::FETCH_ASSOC);
$cats_in  = $pdo->query("SELECT id, category_name_bn, category_name FROM cash_categories WHERE direction='IN'  AND is_active=1 ORDER BY sort_order")->fetchAll(PDO::FETCH_ASSOC);
$cats_out = $pdo->query("SELECT id, category_name_bn, category_name FROM cash_categories WHERE direction='OUT' AND is_active=1 ORDER BY sort_order")->fetchAll(PDO::FETCH_ASSOC);

$base_url = '//'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['SCRIPT_NAME']),'/');
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>ক্যাশ এন্ট্রি — বধুবরণ জুয়েলার্স</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+Bengali:wght@400;600;700&display=swap" rel="stylesheet">
<style>
/* ══ Dashboard-এর সাথে হুবহু Dark Theme ══ */
:root{
  --bg:    #0b1622;
  --bg2:   #111d2c;
  --border:#1e3048;
  --gold:  #d4a843;
  --gold2: #f0c857;
  --green: #27ae60;
  --green2:#1a7a42;
  --red:   #e74c3c;
  --red2:  #9b2020;
  --blue:  #3498db;
  --text:  #e8eef5;
  --text2: #8fa3b8;
  --text3: #4a6278;
}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Noto Serif Bengali',serif;background:var(--bg);color:var(--text);font-size:14px;padding-bottom:90px;}

/* Topbar — dashboard-এর মতো */
.topbar{background:var(--bg2);padding:0 16px;height:54px;display:flex;align-items:center;gap:10px;position:sticky;top:0;z-index:200;border-bottom:2px solid var(--gold);box-shadow:0 2px 16px rgba(0,0,0,.5);}
.topbar h1{font-size:15px;font-weight:700;color:var(--text);flex:1;}
.topbar a{color:var(--gold);text-decoration:none;font-size:12px;font-weight:600;padding:5px 10px;border:1px solid rgba(212,168,67,.3);border-radius:6px;}

.container{max-width:680px;margin:0 auto;padding:14px 12px;}

/* Direction tabs */
.dir-tabs{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:14px;}
.dir-tab{padding:13px;border-radius:10px;border:2px solid var(--border);background:var(--bg2);color:var(--text3);font-size:13px;font-weight:700;cursor:pointer;text-align:center;transition:all .15s;font-family:inherit;}
.dir-tab.in.on {background:rgba(39,174,96,.15);border-color:var(--green);color:var(--green);}
.dir-tab.out.on{background:rgba(231,76,60,.15); border-color:var(--red);  color:var(--red);}

/* Card */
.card{background:var(--bg2);border-radius:11px;padding:14px 16px;margin-bottom:12px;border:1px solid var(--border);}
.card-title{font-size:10px;font-weight:700;color:var(--text3);text-transform:uppercase;letter-spacing:.7px;padding-bottom:8px;margin-bottom:12px;border-bottom:1px solid var(--border);}

/* Form */
.fg{margin-bottom:11px;}
.fg label{display:block;font-size:10px;font-weight:700;color:var(--text3);margin-bottom:5px;text-transform:uppercase;letter-spacing:.5px;}
.fg input,.fg select{width:100%;padding:10px 12px;border:1.5px solid var(--border);border-radius:8px;font-size:14px;color:var(--text);background:#060e1c;outline:none;transition:border .15s;font-family:inherit;}
.fg input:focus,.fg select:focus{border-color:var(--gold);box-shadow:0 0 0 3px rgba(212,168,67,.12);}
.fg select option{background:#0f1a30;}
.fg input::placeholder{color:var(--text3);}
.fr{display:grid;grid-template-columns:1fr 1fr;gap:10px;}

/* Amount box */
.amount-wrap{background:rgba(52,152,219,.1);border:1.5px solid rgba(52,152,219,.3);border-radius:10px;padding:12px 14px;margin-bottom:12px;}
.amount-wrap label{font-size:10px;font-weight:700;color:var(--text3);text-transform:uppercase;letter-spacing:.5px;display:block;margin-bottom:6px;}
.amount-wrap input{width:100%;background:transparent;border:none;outline:none;font-size:26px;font-weight:800;color:var(--blue);font-family:inherit;text-align:center;}
.amount-wrap input::placeholder{color:var(--text3);font-size:18px;font-weight:400;}

/* Party search */
.party-wrap{position:relative;}
.party-sel{display:flex;align-items:center;gap:8px;background:rgba(39,174,96,.1);border:1.5px solid rgba(39,174,96,.3);border-radius:8px;padding:9px 11px;}
.psel-name{font-size:13px;font-weight:700;color:var(--green);flex:1;}
.psel-phone{font-size:11px;color:var(--text3);}
.psel-x{width:26px;height:26px;border-radius:50%;background:rgba(231,76,60,.15);border:1px solid rgba(231,76,60,.3);color:var(--red);cursor:pointer;font-size:12px;flex-shrink:0;font-family:inherit;}
.party-dd{position:absolute;top:100%;left:0;right:0;background:#0f1a30;border:1px solid var(--border);border-radius:8px;margin-top:3px;max-height:220px;overflow-y:auto;z-index:20;box-shadow:0 4px 16px rgba(0,0,0,.4);}
.pi{padding:9px 11px;border-bottom:1px solid rgba(26,45,80,.5);cursor:pointer;}
.pi:hover{background:rgba(212,168,67,.06);}
.pi:last-child{border-bottom:none;}
.pi .pn{font-size:13px;font-weight:700;color:var(--text);}
.pi .pp{font-size:11px;color:var(--text3);}
.pl{padding:12px;text-align:center;font-size:12px;color:var(--text3);}

/* Submit */
.btn-sub{width:100%;padding:14px;border:none;border-radius:10px;font-size:15px;font-weight:800;cursor:pointer;font-family:inherit;transition:transform .12s;border-bottom:3px solid rgba(0,0,0,.3);}
.btn-sub:active{transform:scale(.98);}
.btn-sub:disabled{opacity:.5;cursor:not-allowed;}
.btn-in {background:linear-gradient(135deg,#27ae60,#1e8449);color:#fff;border-bottom-color:#1a5c36;}
.btn-out{background:linear-gradient(135deg,#e74c3c,#c0392b);color:#fff;border-bottom-color:#922b21;}

/* Alert */
.alert{padding:11px 14px;border-radius:8px;margin-bottom:11px;font-size:13px;font-weight:600;display:none;}
.a-ok {background:rgba(39,174,96,.15);color:var(--green);border:1px solid rgba(39,174,96,.3);}
.a-err{background:rgba(231,76,60,.15);color:var(--red);  border:1px solid rgba(231,76,60,.3);}

/* Summary */
.sum-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;}
.sc{background:#060e1c;border:1px solid var(--border);border-radius:9px;padding:10px;text-align:center;}
.sl{font-size:10px;color:var(--text3);font-weight:600;text-transform:uppercase;letter-spacing:.3px;}
.sv{font-size:15px;font-weight:800;margin-top:3px;}

/* Bottom nav — dashboard-এর মতো */
.bnav{position:fixed;bottom:0;left:0;right:0;background:var(--bg2);border-top:2px solid var(--gold);display:flex;z-index:300;padding-bottom:env(safe-area-inset-bottom,0);box-shadow:0 -4px 20px rgba(0,0,0,.4);}
.bn{flex:1;display:flex;flex-direction:column;align-items:center;padding:8px 4px;text-decoration:none;color:var(--text3);font-size:9px;font-weight:600;gap:2px;font-family:inherit;}
.bn.active,.bn:active{color:var(--gold2);}
.bn .bi{font-size:20px;line-height:1;}
</style>
</head>
<body>

<div class="topbar">
  <span style="font-size:18px">💵</span>
  <h1>ক্যাশ এন্ট্রি</h1>
  <a href="index.php">← হোম</a>
</div>

<div class="container">

  <div class="dir-tabs">
    <button class="dir-tab in on" id="tab-in"  onclick="setDir('IN')">⬇️ টাকা আসা (IN)</button>
    <button class="dir-tab out"   id="tab-out" onclick="setDir('OUT')">⬆️ টাকা যাওয়া (OUT)</button>
  </div>

  <div class="card">
    <div class="card-title" id="form-title">💰 ক্যাশ ইন এন্ট্রি</div>

    <div id="a-ok"  class="alert a-ok"></div>
    <div id="a-err" class="alert a-err"></div>

    <!-- Category -->
    <div class="fg">
      <label>ক্যাটাগরি *</label>
      <select id="category_id">
        <option value="">-- নির্বাচন করুন --</option>
        <?php foreach ($cats_in as $c): ?>
        <option value="<?= $c['id'] ?>" data-dir="IN"><?= htmlspecialchars($c['category_name_bn']?:$c['category_name']) ?></option>
        <?php endforeach; ?>
        <?php foreach ($cats_out as $c): ?>
        <option value="<?= $c['id'] ?>" data-dir="OUT" style="display:none"><?= htmlspecialchars($c['category_name_bn']?:$c['category_name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <!-- Account -->
    <div class="fg">
      <label>অ্যাকাউন্ট *</label>
      <select id="account_id">
        <option value="">-- নির্বাচন করুন --</option>
        <?php foreach ($accounts as $acc): ?>
        <option value="<?= $acc['id'] ?>">
          <?= htmlspecialchars($acc['account_name_bn']?:$acc['account_name']) ?>
          (৳<?= number_format($acc['current_balance'],0) ?>)
        </option>
        <?php endforeach; ?>
      </select>
    </div>

    <!-- Party search -->
    <div class="fg">
      <label>পার্টি (ঐচ্ছিক)</label>
      <div class="party-wrap" id="partyWrap">
        <div class="party-sel" id="partySel" style="display:none">
          <div style="flex:1"><div class="psel-name" id="pselName"></div><div class="psel-phone" id="pselPhone"></div></div>
          <button class="psel-x" onclick="clearParty()">✕</button>
        </div>
        <input type="text" id="partySearch" placeholder="🔍 নাম বা ফোন দিয়ে খুঁজুন..."
               autocomplete="off" oninput="onPartySearch()">
        <div class="party-dd" id="partyDD" style="display:none">
          <div id="partyResults"></div>
        </div>
        <input type="hidden" id="party_id">
      </div>
    </div>

    <!-- Amount -->
    <div class="amount-wrap">
      <label>টাকার পরিমাণ (৳) *</label>
      <input type="number" id="amount" min="0" step="1" placeholder="০" inputmode="decimal">
    </div>

    <!-- Date + Note -->
    <div class="fr">
      <div class="fg">
        <label>তারিখ</label>
        <input type="date" id="txn_date" value="<?= date('Y-m-d') ?>">
      </div>
      <div class="fg">
        <label>নোট (ঐচ্ছিক)</label>
        <input type="text" id="note" placeholder="বিস্তারিত...">
      </div>
    </div>

    <button class="btn-sub btn-in" id="btn-sub">💾 সেভ করুন — ক্যাশ ইন</button>
  </div>

  <!-- Today summary -->
  <div class="card">
    <div class="card-title">📊 আজকের সারসংক্ষেপ</div>
    <div class="sum-grid">
      <div class="sc"><div class="sl">▲ IN</div><div class="sv" style="color:var(--green)" id="s-in">—</div></div>
      <div class="sc"><div class="sl">▼ OUT</div><div class="sv" style="color:var(--red)" id="s-out">—</div></div>
      <div class="sc"><div class="sl">= নেট</div><div class="sv" style="color:var(--blue)" id="s-net">—</div></div>
    </div>
  </div>

</div>

<!-- Bottom Nav -->
<div class="bnav">
  <a href="index.php"           class="bn"><span class="bi">🏠</span>হোম</a>
  <a href="ui/pledges.html"     class="bn"><span class="bi">🔒</span>বন্ধক</a>
  <a href="ui/sales.html"       class="bn"><span class="bi">🛍️</span>বিক্রয়</a>
  <a href="pledge_interest.php" class="bn"><span class="bi">📈</span>সুদ</a>
  <a href="cash_daily.php"      class="bn"><span class="bi">📊</span>হিসাব</a>
  <a href="cash_entry.php"      class="bn active"><span class="bi">💵</span>Cash</a>
</div>

<script>
const BASE = '<?= $base_url ?>';
let curDir = 'IN';
let debounce = null;

function loadSummary() {
    fetch(BASE+'/api/cash/daily_summary.php',{credentials:'same-origin'})
    .then(r=>r.json()).then(d=>{
        if(!d.ok)return; d={success:true,total_in:d.data.total_in,total_out:d.data.total_out};
        const f=n=>'৳'+Number(n||0).toLocaleString('en-BD',{maximumFractionDigits:0});
        document.getElementById('s-in').textContent  = f(d.total_in);
        document.getElementById('s-out').textContent = f(d.total_out);
        document.getElementById('s-net').textContent = f((d.total_in||0)-(d.total_out||0));
    }).catch(()=>{});
}
loadSummary();

function setDir(dir){
    curDir=dir;
    document.getElementById('tab-in').className  = 'dir-tab in'  +(dir==='IN'?' on':'');
    document.getElementById('tab-out').className = 'dir-tab out' +(dir==='OUT'?' on':'');
    document.getElementById('form-title').textContent = dir==='IN'?'💰 ক্যাশ ইন এন্ট্রি':'💸 ক্যাশ আউট এন্ট্রি';
    const btn=document.getElementById('btn-sub');
    btn.className='btn-sub '+(dir==='IN'?'btn-in':'btn-out');
    btn.textContent=dir==='IN'?'💾 সেভ করুন — ক্যাশ ইন':'💾 সেভ করুন — ক্যাশ আউট';
    document.querySelectorAll('#category_id option').forEach(o=>{
        if(!o.value)return;
        o.style.display=o.dataset.dir===dir?'':'none';
    });
    document.getElementById('category_id').value='';
}

function onPartySearch(){
    clearTimeout(debounce);
    const q=document.getElementById('partySearch').value.trim();
    if(q.length<1){document.getElementById('partyDD').style.display='none';return;}
    document.getElementById('partyDD').style.display='block';
    document.getElementById('partyResults').innerHTML='<div class="pl">🔍 খুঁজছি...</div>';
    debounce=setTimeout(()=>{
        fetch(BASE+'/api/parties/search_party.php?q='+encodeURIComponent(q)+'&limit=10',{credentials:'same-origin'})
        .then(r=>r.json()).then(d=>{
            const list=d.parties||[];
            if(!list.length){document.getElementById('partyResults').innerHTML='<div class="pl">কোনো পার্টি পাওয়া যায়নি।</div>';return;}
            document.getElementById('partyResults').innerHTML=list.map(p=>
                `<div class="pi" onclick="selParty(${p.id},'${p.name.replace(/'/g,"\\'")}','${(p.phone||'').replace(/'/g,"\\'")}')">
                    <div class="pn">${p.name}</div><div class="pp">${p.phone||''}</div>
                </div>`
            ).join('');
        }).catch(()=>{});
    },300);
}
function selParty(id,name,phone){
    document.getElementById('party_id').value=id;
    document.getElementById('pselName').textContent=name;
    document.getElementById('pselPhone').textContent=phone?'📞 '+phone:'';
    document.getElementById('partySearch').style.display='none';
    document.getElementById('partySel').style.display='flex';
    document.getElementById('partyDD').style.display='none';
}
function clearParty(){
    document.getElementById('party_id').value='';
    document.getElementById('partySearch').value='';
    document.getElementById('partySearch').style.display='block';
    document.getElementById('partySel').style.display='none';
}
document.addEventListener('click',function(e){
    if(!document.getElementById('partyWrap').contains(e.target))
        document.getElementById('partyDD').style.display='none';
});

document.addEventListener('click',function(e){
    if(e.target.closest('#btn-sub')) submit();
});

function submit(){
    const cat=document.getElementById('category_id').value;
    const acc=document.getElementById('account_id').value;
    const amt=parseFloat(document.getElementById('amount').value)||0;
    const date=document.getElementById('txn_date').value;
    const note=document.getElementById('note').value.trim();
    const party=document.getElementById('party_id').value;

    document.getElementById('a-ok').style.display='none';
    document.getElementById('a-err').style.display='none';

    if(!cat){showErr('ক্যাটাগরি নির্বাচন করুন।');return;}
    if(!acc){showErr('অ্যাকাউন্ট নির্বাচন করুন।');return;}
    if(amt<=0){showErr('টাকার পরিমাণ দিন।');return;}

    const btn=document.getElementById('btn-sub');
    btn.disabled=true;
    btn.textContent='⏳ সেভ হচ্ছে…';

    const fd=new FormData();
    fd.append('direction',curDir);
    fd.append('category_id',cat);
    fd.append('cash_account_id',acc);
    fd.append('amount',amt);
    fd.append('transaction_date',date);
    fd.append('note',note);
    if(party)fd.append('party_id',party);

    fetch(BASE+'/api/cash/cash_add.php',{method:'POST',body:fd,credentials:'same-origin'})
    .then(r=>r.json()).then(d=>{
        if(d.success){
            document.getElementById('a-ok').textContent='✅ সেভ হয়েছে! '+(curDir==='IN'?'ক্যাশ ইন':'ক্যাশ আউট')+': ৳'+amt.toLocaleString('en-BD');
            document.getElementById('a-ok').style.display='block';
            document.getElementById('amount').value='';
            document.getElementById('note').value='';
            document.getElementById('category_id').value='';
            clearParty();
            loadSummary();
            setTimeout(()=>document.getElementById('a-ok').style.display='none',4000);
        }else{showErr(d.message||'অজানা ত্রুটি।');}
        btn.disabled=false;
        btn.textContent=curDir==='IN'?'💾 সেভ করুন — ক্যাশ ইন':'💾 সেভ করুন — ক্যাশ আউট';
    }).catch(err=>{
        showErr('Error: '+err.message);
        btn.disabled=false;
        btn.textContent=curDir==='IN'?'💾 সেভ করুন — ক্যাশ ইন':'💾 সেভ করুন — ক্যাশ আউট';
    });
}
function showErr(m){const e=document.getElementById('a-err');e.textContent=m;e.style.display='block';}
</script>
</body>
</html>
