<?php
/**
 * cash_daily.php  (root page)
 * Upload: /home/jewellersbd/public_html/erp.jewellersbd.com/cash_daily.php
 * দিন শেষের cash summary + closing
 */
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; }

$today    = date('Y-m-d');
$sel_date = $_GET['date'] ?? $today;
$user_id  = $_SESSION['user_id'] ?? 1;
$ip       = $_SERVER['REMOTE_ADDR'] ?? '';
$base_url = '//'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['SCRIPT_NAME']),'/');

// ── সব active accounts ────────────────────────────────────────
$accounts = $pdo->query("SELECT * FROM cash_accounts WHERE is_active=1 AND deleted_at IS NULL ORDER BY sort_order,id")->fetchAll(PDO::FETCH_ASSOC);

// ── প্রতিটা account-এর আজকের IN/OUT ─────────────────────────
$summary = [];
foreach ($accounts as $acc) {
    $aid = $acc['id'];

    // আজকের transactions
    $txn = $pdo->prepare("
        SELECT
            SUM(CASE WHEN direction='IN'  AND is_deleted=0 THEN amount ELSE 0 END) AS total_in,
            SUM(CASE WHEN direction='OUT' AND is_deleted=0 THEN amount ELSE 0 END) AS total_out,
            COUNT(CASE WHEN is_deleted=0 THEN 1 END) AS txn_count
        FROM cash_transactions
        WHERE cash_account_id=? AND transaction_date=?
    ");
    $txn->execute([$aid, $sel_date]);
    $day = $txn->fetch(PDO::FETCH_ASSOC);

    // Category breakdown (top 5)
    $cats = $pdo->prepare("
        SELECT cc.category_name_bn AS cat, ct.direction, SUM(ct.amount) AS total
        FROM cash_transactions ct
        LEFT JOIN cash_categories cc ON cc.id=ct.category_id
        WHERE ct.cash_account_id=? AND ct.transaction_date=? AND ct.is_deleted=0
        GROUP BY ct.category_id, ct.direction
        ORDER BY total DESC
        LIMIT 10
    ");
    $cats->execute([$aid, $sel_date]);
    $breakdown = $cats->fetchAll(PDO::FETCH_ASSOC);

    // আগের দিনের closing balance (opening হিসেবে)
    $prev = $pdo->prepare("
        SELECT calculated_balance FROM cash_daily_closing
        WHERE cash_account_id=? AND closing_date < ?
        ORDER BY closing_date DESC LIMIT 1
    ");
    $prev->execute([$aid, $sel_date]);
    $prev_close = $prev->fetchColumn();
    $opening = $prev_close !== false ? (float)$prev_close : (float)$acc['opening_balance'];

    // আজকের closing আছে কিনা
    $closed = $pdo->prepare("SELECT * FROM cash_daily_closing WHERE cash_account_id=? AND closing_date=? LIMIT 1");
    $closed->execute([$aid, $sel_date]);
    $closing_rec = $closed->fetch(PDO::FETCH_ASSOC);

    $total_in  = (float)($day['total_in']  ?? 0);
    $total_out = (float)($day['total_out'] ?? 0);
    $calc_balance = $opening + $total_in - $total_out;

    $summary[] = [
        'account'       => $acc,
        'opening'       => $opening,
        'total_in'      => $total_in,
        'total_out'     => $total_out,
        'calc_balance'  => $calc_balance,
        'current_bal'   => (float)$acc['current_balance'],
        'txn_count'     => (int)($day['txn_count'] ?? 0),
        'breakdown'     => $breakdown,
        'closing'       => $closing_rec,
        'is_closed'     => !empty($closing_rec),
    ];
}

// Grand totals
$grand_in  = array_sum(array_column($summary, 'total_in'));
$grand_out = array_sum(array_column($summary, 'total_out'));
$grand_bal = array_sum(array_column($summary, 'calc_balance'));

// আজকের সব transactions (recent 20)
$recent = $pdo->prepare("
    SELECT ct.*, ca.account_name, cc.category_name_bn AS cat_name, cc.direction AS cat_dir
    FROM cash_transactions ct
    LEFT JOIN cash_accounts ca  ON ca.id=ct.cash_account_id
    LEFT JOIN cash_categories cc ON cc.id=ct.category_id
    WHERE ct.transaction_date=? AND ct.is_deleted=0
    ORDER BY ct.created_at DESC
    LIMIT 30
");
$recent->execute([$sel_date]);
$recent_txns = $recent->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Cash Daily Summary — <?= $sel_date ?></title>
<style>
:root{--navy:#1e2a3b;--navy2:#243447;--gold:#d4a843;--gold-lt:#fef3c7;--gold-dk:#92710c;--green:#22c55e;--green-lt:#dcfce7;--red:#ef4444;--red-lt:#fee2e2;--blue:#3b82f6;--blue-lt:#eff6ff;--text:#1e293b;--muted:#64748b;--border:#e2e8f0;--surface:#f8fafc;}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Segoe UI',system-ui,sans-serif;background:var(--surface);color:var(--text);font-size:14px;}
.topbar{background:var(--navy);padding:0 16px;height:52px;display:flex;align-items:center;gap:10px;position:sticky;top:0;z-index:100;border-bottom:2px solid var(--gold);}
.topbar h1{font-size:15px;font-weight:700;color:#fff;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,.4);border-radius:6px;}
.container{max-width:720px;margin:0 auto;padding:14px 12px 60px;}

/* Date nav */
.date-nav{display:flex;align-items:center;gap:8px;margin-bottom:14px;}
.date-nav input[type=date]{flex:1;padding:9px 12px;border:1.5px solid var(--border);border-radius:7px;font-size:14px;outline:none;}
.date-nav input:focus{border-color:var(--gold);}
.btn-go{padding:9px 16px;background:var(--navy);color:#fff;border:none;border-radius:7px;font-size:13px;font-weight:700;cursor:pointer;border-bottom:2px solid var(--gold);}
.btn-today{padding:9px 12px;background:var(--gold);color:var(--navy);border:none;border-radius:7px;font-size:12px;font-weight:800;cursor:pointer;}

/* Grand summary */
.grand-bar{display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-bottom:14px;}
.gb-card{background:#fff;border:1px solid var(--border);border-radius:10px;padding:12px 14px;text-align:center;}
.gb-label{font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;letter-spacing:.4px;}
.gb-val{font-size:18px;font-weight:800;margin-top:3px;}
.gb-in  .gb-val{color:#15803d;}
.gb-out .gb-val{color:var(--red);}
.gb-bal .gb-val{color:var(--blue);}

/* Account card */
.acc-card{background:#fff;border:1px solid var(--border);border-radius:10px;margin-bottom:10px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,.05);}
.acc-card.closed-card{border-left:4px solid #15803d;}
.acc-card.open-card{border-left:4px solid var(--gold);}
.acc-header{background:var(--navy);padding:10px 16px;display:flex;justify-content:space-between;align-items:center;}
.acc-name{font-size:14px;font-weight:700;color:#fff;}
.acc-type{font-size:10px;color:rgba(255,255,255,.5);margin-top:1px;}
.acc-badge{font-size:11px;font-weight:700;padding:3px 10px;border-radius:20px;}
.badge-closed{background:#dcfce7;color:#15803d;}
.badge-open{background:var(--gold-lt);color:var(--gold-dk);}

.acc-body{padding:14px 16px;}
.acc-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px 12px;margin-bottom:12px;}
.ag-item label{font-size:10px;color:var(--muted);text-transform:uppercase;letter-spacing:.3px;display:block;}
.ag-item .v{font-size:14px;font-weight:700;}
.v-in{color:#15803d;}
.v-out{color:var(--red);}
.v-bal{color:var(--blue);}
.v-open{color:var(--muted);}

/* Breakdown */
.breakdown{margin-bottom:12px;}
.breakdown-title{font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;margin-bottom:6px;}
.bd-row{display:flex;justify-content:space-between;font-size:12px;padding:3px 0;border-bottom:1px solid var(--surface);}
.bd-row:last-child{border-bottom:none;}
.bd-cat{color:var(--text);}
.bd-in{color:#15803d;font-weight:600;}
.bd-out{color:var(--red);font-weight:600;}

/* Close form */
.close-form{background:var(--gold-lt);border:1px solid #fcd34d;border-radius:8px;padding:12px 14px;}
.close-form-title{font-size:11px;font-weight:700;color:var(--gold-dk);text-transform:uppercase;margin-bottom:8px;}
.cf-row{display:flex;gap:8px;align-items:flex-end;}
.cf-input{flex:1;}
.cf-input label{font-size:10px;color:var(--gold-dk);font-weight:700;display:block;margin-bottom:3px;text-transform:uppercase;}
.cf-input input{width:100%;padding:8px 10px;border:1.5px solid #fcd34d;border-radius:6px;font-size:14px;background:#fff;outline:none;}
.cf-input input:focus{border-color:var(--gold);}
.btn-close-day{padding:9px 14px;background:var(--navy);color:#fff;border:none;border-radius:7px;font-size:13px;font-weight:700;cursor:pointer;border-bottom:2px solid var(--gold);white-space:nowrap;}
.btn-close-day:disabled{background:#94a3b8;border-bottom-color:#64748b;cursor:not-allowed;}

/* Already closed info */
.closed-info{background:var(--green-lt);border:1px solid #86efac;border-radius:8px;padding:10px 14px;}
.ci-row{display:flex;justify-content:space-between;font-size:12px;padding:2px 0;}
.ci-label{color:var(--muted);}
.ci-diff-pos{color:#15803d;font-weight:700;}
.ci-diff-neg{color:var(--red);font-weight:700;}

/* Recent transactions */
.section-title{font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.6px;margin-bottom:10px;padding-bottom:6px;border-bottom:1px solid var(--border);}
.txn-table{width:100%;border-collapse:collapse;font-size:12px;}
.txn-table th{background:var(--navy);color:rgba(255,255,255,.8);padding:7px 8px;text-align:left;font-size:10px;text-transform:uppercase;letter-spacing:.4px;}
.txn-table th:last-child{text-align:right;}
.txn-table td{padding:7px 8px;border-bottom:1px solid var(--border);}
.txn-table tr:last-child td{border-bottom:none;}
.txn-in{color:#15803d;font-weight:700;}
.txn-out{color:var(--red);font-weight:700;}
.txn-note{font-size:11px;color:var(--muted);}

.card{background:#fff;border:1px solid var(--border);border-radius:10px;padding:14px 16px;margin-bottom:12px;}
.empty-txn{text-align:center;color:var(--muted);padding:20px;font-size:13px;}

/* Alert */
.alert{padding:10px 14px;border-radius:7px;margin-bottom:8px;font-size:13px;display:none;font-weight:500;}
.alert-success{background:var(--green-lt);color:#15803d;border:1px solid #86efac;}
.alert-error{background:var(--red-lt);color:#b91c1c;border:1px solid #fca5a5;}
</style>
</head>
<body>
<div class="topbar">
  <span style="font-size:18px">💼</span>
  <h1>Cash Daily Summary</h1>
  <a href="index.php">Dashboard</a>
</div>

<div class="container">

  <!-- Date nav -->
  <div class="date-nav">
    <input type="date" id="date-input" value="<?= $sel_date ?>" max="<?= $today ?>">
    <button class="btn-go" onclick="goDate()">দেখুন</button>
    <button class="btn-today" onclick="document.getElementById('date-input').value='<?= $today ?>';goDate()">আজ</button>
  </div>

  <!-- Grand totals -->
  <div class="grand-bar">
    <div class="gb-card gb-in">
      <div class="gb-label">▲ মোট IN</div>
      <div class="gb-val">৳<?= number_format($grand_in, 0) ?></div>
    </div>
    <div class="gb-card gb-out">
      <div class="gb-label">▼ মোট OUT</div>
      <div class="gb-val">৳<?= number_format($grand_out, 0) ?></div>
    </div>
    <div class="gb-card gb-bal">
      <div class="gb-label">= নেট ব্যালেন্স</div>
      <div class="gb-val">৳<?= number_format($grand_bal, 0) ?></div>
    </div>
  </div>

  <!-- Per-account cards -->
  <?php foreach ($summary as $s): $acc = $s['account']; ?>
  <div class="acc-card <?= $s['is_closed'] ? 'closed-card' : 'open-card' ?>">
    <div class="acc-header">
      <div>
        <div class="acc-name"><?= htmlspecialchars($acc['account_name_bn'] ?: $acc['account_name']) ?></div>
        <div class="acc-type"><?= $acc['account_type'] ?> · <?= $s['txn_count'] ?> টি লেনদেন</div>
      </div>
      <span class="acc-badge <?= $s['is_closed'] ? 'badge-closed' : 'badge-open' ?>">
        <?= $s['is_closed'] ? '✓ বন্ধ' : '● খোলা' ?>
      </span>
    </div>
    <div class="acc-body">
      <div class="acc-grid">
        <div class="ag-item"><label>শুরুর ব্যালেন্স</label><span class="v v-open">৳<?= number_format($s['opening'], 2) ?></span></div>
        <div class="ag-item"><label>বর্তমান ব্যালেন্স</label><span class="v v-bal">৳<?= number_format($s['current_bal'], 2) ?></span></div>
        <div class="ag-item"><label>▲ আজকের IN</label><span class="v v-in">৳<?= number_format($s['total_in'], 2) ?></span></div>
        <div class="ag-item"><label>▼ আজকের OUT</label><span class="v v-out">৳<?= number_format($s['total_out'], 2) ?></span></div>
      </div>

      <!-- System calculated balance highlight -->
      <div style="background:var(--blue-lt);border:1px solid #bfdbfe;border-radius:7px;padding:9px 12px;display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
        <span style="font-size:12px;font-weight:700;color:#1e40af">হিসাব করা ব্যালেন্স</span>
        <span style="font-size:17px;font-weight:800;color:var(--blue)">৳<?= number_format($s['calc_balance'], 2) ?></span>
      </div>

      <!-- Category breakdown -->
      <?php if (!empty($s['breakdown'])): ?>
      <div class="breakdown">
        <div class="breakdown-title">বিভাগ অনুযায়ী</div>
        <?php foreach ($s['breakdown'] as $bd): ?>
        <div class="bd-row">
          <span class="bd-cat"><?= htmlspecialchars($bd['cat'] ?? 'অন্যান্য') ?></span>
          <span class="<?= $bd['direction']==='IN' ? 'bd-in' : 'bd-out' ?>">
            <?= $bd['direction']==='IN' ? '+' : '−' ?>৳<?= number_format($bd['total'], 0) ?>
          </span>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <div id="alert-s-<?= $acc['id'] ?>" class="alert alert-success"></div>
      <div id="alert-e-<?= $acc['id'] ?>" class="alert alert-error"></div>

      <!-- Close form or closed info -->
      <?php if ($s['is_closed']): $cl = $s['closing']; ?>
      <div class="closed-info">
        <div style="font-size:11px;font-weight:700;color:#15803d;margin-bottom:6px">✓ দিন বন্ধ করা হয়েছে</div>
        <div class="ci-row"><span class="ci-label">গণনা করা ব্যালেন্স</span><span>৳<?= number_format($cl['calculated_balance'],2) ?></span></div>
        <?php if ($cl['physical_count'] !== null): ?>
        <div class="ci-row"><span class="ci-label">গণনা করা নগদ (physical)</span><span>৳<?= number_format($cl['physical_count'],2) ?></span></div>
        <div class="ci-row">
          <span class="ci-label">পার্থক্য</span>
          <span class="<?= $cl['difference'] >= 0 ? 'ci-diff-pos' : 'ci-diff-neg' ?>">
            <?= $cl['difference'] >= 0 ? '+' : '' ?>৳<?= number_format($cl['difference'],2) ?>
          </span>
        </div>
        <?php endif; ?>
        <?php if ($cl['difference_reason']): ?>
        <div class="ci-row"><span class="ci-label">কারণ</span><span><?= htmlspecialchars($cl['difference_reason']) ?></span></div>
        <?php endif; ?>
      </div>
      <?php elseif ($sel_date <= $today): ?>
      <div class="close-form">
        <div class="close-form-title">🔒 দিন বন্ধ করুন — <?= $sel_date ?></div>
        <div class="cf-row">
          <div class="cf-input">
            <label>Physical Count (ড্রয়ারে যত টাকা)</label>
            <input type="number" id="physical-<?= $acc['id'] ?>" step="0.01" min="0"
                   value="<?= number_format($s['calc_balance'], 2, '.', '') ?>"
                   placeholder="<?= number_format($s['calc_balance'], 2, '.', '') ?>" inputmode="decimal">
          </div>
          <button class="btn-close-day" id="btn-close-<?= $acc['id'] ?>"
                  onclick="closeDay(<?= $acc['id'] ?>, '<?= $sel_date ?>', <?= $s['calc_balance'] ?>)">
            বন্ধ করুন
          </button>
        </div>
        <div style="font-size:11px;color:var(--gold-dk);margin-top:6px">
          Physical count না দিলে calculated balance দিয়েই বন্ধ হবে।
        </div>
      </div>
      <?php endif; ?>
    </div>
  </div>
  <?php endforeach; ?>

  <!-- Recent transactions -->
  <div class="card">
    <div class="section-title">📋 আজকের লেনদেন (সর্বশেষ ৩০টি)</div>
    <?php if (empty($recent_txns)): ?>
    <div class="empty-txn">আজ কোনো লেনদেন নেই।</div>
    <?php else: ?>
    <div style="overflow-x:auto">
    <table class="txn-table">
      <thead>
        <tr>
          <th>সময়</th>
          <th>Account</th>
          <th>বিভাগ</th>
          <th>মন্তব্য</th>
          <th style="text-align:right">টাকা</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($recent_txns as $t): ?>
        <tr>
          <td style="white-space:nowrap;color:var(--muted);font-size:11px"><?= date('h:i A', strtotime($t['created_at'])) ?></td>
          <td style="font-size:12px"><?= htmlspecialchars($t['account_name']) ?></td>
          <td style="font-size:11px;color:var(--muted)"><?= htmlspecialchars($t['cat_name'] ?? '—') ?></td>
          <td><div class="txn-note"><?= htmlspecialchars(mb_substr($t['note'] ?? '', 0, 30)) ?></div></td>
          <td class="<?= $t['direction']==='IN' ? 'txn-in' : 'txn-out' ?>" style="text-align:right;white-space:nowrap">
            <?= $t['direction']==='IN' ? '+' : '−' ?>৳<?= number_format((float)$t['amount'], 0) ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    </div>
    <?php endif; ?>
  </div>

</div>

<script>
const BASE = '<?= $base_url ?>';

function goDate() {
    const d = document.getElementById('date-input').value;
    if (d) location.href = location.pathname + '?date=' + d;
}
document.addEventListener('keydown', function(e) {
    if (e.key === 'Enter' && e.target.id === 'date-input') goDate();
});

function closeDay(accountId, date, calcBalance) {
    const physical = parseFloat(document.getElementById('physical-' + accountId).value) || calcBalance;
    const btn = document.getElementById('btn-close-' + accountId);

    if (!confirm('নিশ্চিত? ' + date + ' এর জন্য এই account বন্ধ করবেন?')) return;

    btn.disabled = true;
    btn.textContent = '⏳ বন্ধ হচ্ছে…';

    const fd = new FormData();
    fd.append('account_id',     accountId);
    fd.append('closing_date',   date);
    fd.append('calc_balance',   calcBalance);
    fd.append('physical_count', physical);

    fetch(BASE + '/api/cash/day_close.php', { method: 'POST', body: fd })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                document.getElementById('alert-s-' + accountId).textContent = '✅ ' + data.message;
                document.getElementById('alert-s-' + accountId).style.display = 'block';
                setTimeout(() => location.reload(), 1500);
            } else {
                document.getElementById('alert-e-' + accountId).textContent = data.message;
                document.getElementById('alert-e-' + accountId).style.display = 'block';
                btn.disabled = false;
                btn.textContent = 'বন্ধ করুন';
            }
        })
        .catch(err => {
            document.getElementById('alert-e-' + accountId).textContent = 'Error: ' + err.message;
            document.getElementById('alert-e-' + accountId).style.display = 'block';
            btn.disabled = false;
            btn.textContent = 'বন্ধ করুন';
        });
}
</script>
</body>
</html>