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

$zdb    = $_SESSION["zdbyear_" . $dbname];
$compcd = $_SESSION["comp_"    . $dbname];
mysqli_select_db($conn, $zdb);

// ── Auto-migration ─────────────────────────────────────────────────────────
foreach (['arrivaldate'=>"date NULL DEFAULT NULL", 'arrivalgodown'=>"int(11) NOT NULL DEFAULT 0"] as $col=>$def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `despatch` LIKE '$col'");
    if ($chk && mysqli_num_rows($chk) == 0)
        mysqli_query($conn, "ALTER TABLE `despatch` ADD COLUMN `$col` $def");
}

// ── POST: Update arrival date ─────────────────────────────────────────────
if (isset($_POST['update_arrival'])) {
    $dspVouch    = (int)$_POST['dspvouchno'];
    $arrDate     = trim($_POST['arrivaldate'] ?? '');
    $arrGodown   = (int)($_POST['arrivalgodown'] ?? 0);

    if ($dspVouch > 0 && $arrDate != '' && $arrGodown > 0) {
        // Save arrival date and godown
        mysqli_query($conn, "UPDATE `despatch` SET `arrivaldate`='$arrDate', `arrivalgodown`='$arrGodown'
                              WHERE `vouchno`='$dspVouch'") or die(mysqli_error($conn));

        // Get despatch info for stock posting
        $dspRes = mysqli_query($conn, "SELECT * FROM `despatch` WHERE `vouchno`='$dspVouch'");
        $dsp    = mysqli_fetch_assoc($dspRes) ?: [];
        $customer = (int)($dsp['customer'] ?? 0);

        // Delete any previous arrival stock entries for this despatch
        mysqli_query($conn, "DELETE FROM `stockledger` WHERE `source`='ARR' AND `vouchno`='$dspVouch'");

        // Post packlist rows as stock-in at India godown
        $plRes = mysqli_query($conn, "SELECT * FROM `packlist` WHERE `dspvouchno`='$dspVouch'");
        while ($pl = mysqli_fetch_assoc($plRes)) {
            $d    = mysqli_real_escape_string($conn, $pl['description']);
            $sm   = mysqli_real_escape_string($conn, $pl['shipmark']);
            $ctn  = (float)$pl['ctn'];
            $tqty = (float)$pl['tqty'];
            $tcbm = (float)$pl['cbm'];
            $twt  = (float)$pl['weight'];
            if ($ctn <= 0) continue;
            mysqli_query($conn, "INSERT INTO `stockledger`
                (`vouchdt`,`source`,`vouchno`,`godown`,`customer`,`supplier`,`description`,`modelno`,`marka`,`qty`,`ctn`,`tcbm`,`tweight`)
                VALUES ('$arrDate','ARR','$dspVouch','$arrGodown','$customer','0','$d','','$sm','$tqty','$ctn','$tcbm','$twt')")
            or die(mysqli_error($conn));
        }

        $_SESSION['arrival_msg'] = 'Arrival date updated and stock posted successfully.';
    }
    header("Location: arrival.php");
    exit;
}

$successMsg = '';
if (isset($_SESSION['arrival_msg'])) {
    $successMsg = $_SESSION['arrival_msg'];
    unset($_SESSION['arrival_msg']);
}

// ── Fetch pending arrivals (despatch with no arrivaldate) ─────────────────
$pendingRes = mysqli_query($conn,
    "SELECT d.*, c.name AS custname, ag.name AS shippername
     FROM despatch d
     LEFT JOIN accmast c  ON c.accode  = d.customer
     LEFT JOIN loadingplan lp ON lp.containerno = d.containerno AND d.containerno != ''
     LEFT JOIN accmast ag ON ag.accode = lp.shipper
     WHERE (d.arrivaldate IS NULL OR d.arrivaldate = '0000-00-00')
     ORDER BY d.vouchno DESC") or die(mysqli_error($conn));

$pending = [];
while ($r = mysqli_fetch_assoc($pendingRes)) { $pending[] = $r; }

// India godowns only
$indiaGodowns = [];
$igRes = mysqli_query($conn, "SELECT `code`,`name` FROM `godown` WHERE `country`!='China' ORDER BY `name`");
while ($r = mysqli_fetch_assoc($igRes)) $indiaGodowns[] = $r;

// Get packlist summary per despatch
function getPlSummary($conn, $dspVouch) {
    $res = mysqli_query($conn, "SELECT SUM(ctn) AS totctn, SUM(tqty) AS tottqty,
                                        SUM(cbm) AS totcbm, SUM(weight) AS totwt,
                                        COUNT(*) AS items
                                 FROM packlist WHERE dspvouchno='$dspVouch'");
    $r = mysqli_fetch_assoc($res);
    return $r ?: ['totctn'=>0,'tottqty'=>0,'totcbm'=>0,'totwt'=>0,'items'=>0];
}

include("includes/linkshead.php");
?>
<style>
body { background:#f0f2f5; padding:16px 20px; }
.page-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:18px; flex-wrap:wrap; gap:8px; }
.page-header h2 { font-size:15px; font-weight:700; color:#1e293b; }
.badge-count { background:#f43f5e; color:#fff; font-size:11px; font-weight:700; padding:2px 9px; border-radius:12px; margin-left:8px; }
.success-bar { background:#d1fae5; border:1px solid #6ee7b7; color:#065f46; padding:10px 16px; border-radius:8px; margin-bottom:16px; font-size:13px; font-weight:600; }
.arrival-card { background:#fff; border-radius:12px; box-shadow:0 1px 3px rgba(0,0,0,.07),0 4px 14px rgba(0,0,0,.05); margin-bottom:16px; overflow:hidden; }
.arrival-card-head { padding:14px 18px; border-bottom:1px solid #f1f5f9; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:8px; }
.arrival-card-head .left { display:flex; align-items:center; gap:12px; flex-wrap:wrap; }
.dsp-badge { font-size:12px; font-weight:700; background:#dbeafe; color:#1e40af; padding:4px 12px; border-radius:20px; }
.cnt-badge { font-size:12px; font-weight:700; background:#f3e8ff; color:#6d28d9; padding:4px 12px; border-radius:20px; }
.dt-badge  { font-size:12px; color:#64748b; }
.arrival-card-body { padding:14px 18px; }
.summary-pills { display:flex; flex-wrap:wrap; gap:8px; margin-bottom:14px; }
.pill { padding:5px 14px; border-radius:8px; font-size:12px; font-weight:600; background:#f8fafc; border:1px solid #e2e8f0; color:#374151; }
.pill i { margin-right:5px; opacity:.7; }
.shipper-line { font-size:12.5px; color:#64748b; margin-bottom:14px; }
.shipper-line b { color:#1e293b; }
.arrival-form { display:flex; align-items:flex-end; gap:12px; flex-wrap:wrap; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:14px; }
.arrival-form .fl { display:flex; flex-direction:column; gap:4px; }
.arrival-form label { font-size:11.5px; font-weight:600; color:#64748b; }
.arrival-form input[type=date], .arrival-form select { padding:7px 10px; border:1px solid #e2e8f0; border-radius:6px; font-size:13px; font-family:inherit; color:#1e293b; background:#fff; }
.arrival-form input[type=date]:focus, .arrival-form select:focus { outline:none; border-color:#3b82f6; }
.btn-arrive { padding:8px 20px; background:linear-gradient(135deg,#10b981,#059669); color:#fff; border:none; border-radius:8px; font-size:13px; font-weight:700; cursor:pointer; display:flex; align-items:center; gap:6px; }
.btn-arrive:hover { filter:brightness(1.07); }
.empty-state { text-align:center; padding:48px 20px; color:#94a3b8; }
.empty-state i { font-size:40px; margin-bottom:12px; display:block; color:#cbd5e1; }
</style>
</head>
<body>

<div class="page-header">
    <h2><i class="fa fa-anchor" style="color:#3b82f6;margin-right:8px;"></i>Arrival Update
        <?php if (count($pending) > 0): ?>
        <span class="badge-count"><?php echo count($pending); ?> Pending</span>
        <?php endif; ?>
    </h2>
</div>

<?php if ($successMsg): ?>
<div class="success-bar"><i class="fa fa-check-circle" style="margin-right:8px;"></i><?php echo htmlspecialchars($successMsg); ?></div>
<?php endif; ?>

<?php if (count($pending) == 0): ?>
<div class="empty-state">
    <i class="fa fa-ship"></i>
    <div style="font-size:14px;font-weight:600;color:#64748b;">All arrivals are up to date!</div>
    <div style="font-size:12px;margin-top:6px;">No pending despatch records without an arrival date.</div>
</div>
<?php else: ?>
<?php foreach ($pending as $d):
    $sum = getPlSummary($conn, $d['vouchno']);
    $dt  = ($d['vouchdt'] && $d['vouchdt'] != '0000-00-00') ? date('d-m-Y', strtotime($d['vouchdt'])) : '—';
?>
<div class="arrival-card">
    <div class="arrival-card-head">
        <div class="left">
            <span class="dsp-badge"><i class="fa fa-truck"></i> DSP#<?php echo $d['vouchno']; ?></span>
            <?php if ($d['containerno']): ?>
            <span class="cnt-badge"><i class="fa fa-box"></i> <?php echo htmlspecialchars($d['containerno']); ?></span>
            <?php endif; ?>
            <span class="dt-badge"><i class="fa fa-calendar" style="margin-right:4px;"></i>Dispatched: <b><?php echo $dt; ?></b></span>
        </div>
        <div style="font-size:12px;color:#94a3b8;"><?php echo htmlspecialchars($d['custname'] ?? ''); ?></div>
    </div>
    <div class="arrival-card-body">
        <div class="shipper-line">
            <i class="fa fa-ship" style="margin-right:5px;color:#7c3aed;"></i>
            Shipper / Agent: <b><?php echo htmlspecialchars($d['shippername'] ?? '—'); ?></b>
            <?php if ($d['remarks']): ?> &nbsp;·&nbsp; <?php echo htmlspecialchars($d['remarks']); ?><?php endif; ?>
        </div>
        <div class="summary-pills">
            <span class="pill"><i class="fa fa-boxes-stacked"></i>CTN: <b><?php echo $sum['totctn'] ? number_format((float)$sum['totctn'],0) : '—'; ?></b></span>
            <span class="pill"><i class="fa fa-cubes"></i>T.QTY: <b><?php echo $sum['tottqty'] ? number_format((float)$sum['tottqty'],0) : '—'; ?></b></span>
            <span class="pill"><i class="fa fa-ruler-combined"></i>CBM: <b><?php echo $sum['totcbm'] ? number_format((float)$sum['totcbm'],3) : '—'; ?></b></span>
            <span class="pill"><i class="fa fa-weight-hanging"></i>Weight: <b><?php echo $sum['totwt'] ? number_format((float)$sum['totwt'],2) : '—'; ?></b></span>
            <span class="pill"><i class="fa fa-file-lines"></i>Items: <b><?php echo (int)$sum['items']; ?></b></span>
        </div>
        <form method="POST" action="arrival.php">
            <input type="hidden" name="update_arrival" value="1">
            <input type="hidden" name="dspvouchno" value="<?php echo $d['vouchno']; ?>">
            <div class="arrival-form">
                <div class="fl">
                    <label><i class="fa fa-calendar-check"></i> Arrival Date <span style="color:#ef4444;">*</span></label>
                    <input type="date" name="arrivaldate" required>
                </div>
                <div class="fl">
                    <label><i class="fa fa-warehouse"></i> India Godown <span style="color:#ef4444;">*</span></label>
                    <select name="arrivalgodown" required>
                        <option value="">-- Select Godown --</option>
                        <?php foreach ($indiaGodowns as $g): ?>
                        <option value="<?php echo (int)$g['code']; ?>"><?php echo htmlspecialchars($g['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="btn-arrive"
                    onclick="return confirm('Update arrival date and post stock to selected godown?')">
                    <i class="fa fa-check"></i> Confirm Arrival
                </button>
            </div>
        </form>
    </div>
</div>
<?php endforeach; ?>
<?php endif; ?>

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