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

$formname = 'Damage Register';
$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `damage` (
    `vouchno` INT(11) NOT NULL,
    `vouchdt` DATE NULL,
    `godown` INT(11) NOT NULL DEFAULT 0,
    `remarks` VARCHAR(200) NOT NULL DEFAULT '',
    `totqty` DOUBLE NOT NULL DEFAULT 0,
    `adduser` VARCHAR(50) NOT NULL DEFAULT '',
    `adddate` DATE NULL, `addtime` TIME NULL,
    `edituser` VARCHAR(50) NOT NULL DEFAULT '',
    `editdate` DATE NULL, `edittime` TIME NULL,
    PRIMARY KEY (`vouchno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `damagedtl` (
    `srl` INT(11) NOT NULL AUTO_INCREMENT,
    `vouchno` INT(11) NOT NULL DEFAULT 0,
    `product` INT(11) NOT NULL DEFAULT 0,
    `brand` INT(11) NOT NULL DEFAULT 0,
    `qty` DOUBLE NOT NULL DEFAULT 0,
    PRIMARY KEY (`srl`), KEY `vouchno` (`vouchno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$godown = isset($_POST['godown']) ? (int)$_POST['godown'] : 0;
$search = isset($_POST['search']) ? trim($_POST['search']) : '';
$dtype  = isset($_POST['dtype'])  ? trim($_POST['dtype'])  : '1';
$fdate  = isset($_POST['fdate'])  ? trim($_POST['fdate'])  : '';
$tdate  = isset($_POST['tdate'])  ? trim($_POST['tdate'])  : '';

function toISO($d) {
    $d = trim($d);
    if ($d === '') return '';
    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $d)) return $d;
    if (preg_match('/^(\d{2})-(\d{2})-(\d{4})$/', $d, $m)) return "$m[3]-$m[2]-$m[1]";
    $t = strtotime($d);
    return $t ? date('Y-m-d', $t) : '';
}
$fdateIso = toISO($fdate);
$tdateIso = toISO($tdate);

if ($fdateIso == '') { echo "<script>alert('From Date cannot be empty');window.history.back();</script>"; exit; }
if ($tdateIso == '') { echo "<script>alert('To Date cannot be empty');window.history.back();</script>"; exit; }

$godowncond = ($godown > 0) ? " AND d.godown='$godown' " : '';
$searchcond = '';
if ($search != '') {
    $s = mysqli_real_escape_string($conn, $search);
    $searchcond = " AND p.name LIKE '%$s%' ";
}

function pf($v) { $v=(float)$v; return $v==0?'':number_format($v,2); }

include("includes/linkshead.php");
?>
<style>
body { background:#f0f2f5; margin:0; padding:12px 16px; font-family:inherit; }
.rpt-wrap { background:#fff; border-radius:10px; box-shadow:0 1px 3px rgba(0,0,0,.08); overflow:hidden; max-width:1100px; margin:0 auto; }
.rpt-header { background:#1e293b; color:#fff; padding:14px 20px; display:flex; align-items:center; justify-content:space-between; }
.rpt-header h2 { font-size:15px; font-weight:700; margin:0; }
.rpt-params { font-size:11px; color:#94a3b8; margin-top:4px; }
.rpt-tbl { width:100%; border-collapse:collapse; font-size:12.5px; }
.rpt-tbl thead th { background:#f8fafc; color:#475569; font-weight:700; font-size:11px; text-transform:uppercase; letter-spacing:.04em; padding:9px 12px; border-bottom:2px solid #e2e8f0; text-align:left; white-space:nowrap; }
.rpt-tbl thead th.num { text-align:right; }
.rpt-tbl tbody td { padding:9px 12px; border-bottom:1px solid #f1f5f9; color:#334155; vertical-align:top; }
.rpt-tbl tbody td.num { text-align:right; font-variant-numeric:tabular-nums; }
.rpt-tbl tbody tr:hover { background:#f8fafc; }
.rpt-tbl tfoot td { font-weight:700; background:#f1f5f9; border-top:2px solid #e2e8f0; padding:9px 12px; text-align:right; }
.neg { color:#ea580c; }
.no-data { text-align:center; padding:60px 20px; color:#94a3b8; }
@media print { body { background:#fff; } .rpt-header { background:#1e293b !important; -webkit-print-color-adjust:exact; } }
</style>
</head>
<body>
<div class="rpt-wrap">
    <div class="rpt-header">
        <div>
            <h2><i class="fa fa-triangle-exclamation" style="margin-right:8px;"></i><?php echo $formname; ?></h2>
            <div class="rpt-params">
                From: <?php echo date('d-m-Y', strtotime($fdateIso)); ?>
                &nbsp;|&nbsp; To: <?php echo date('d-m-Y', strtotime($tdateIso)); ?>
                <?php if ($godown > 0): $gn = mysqli_fetch_assoc(mysqli_query($conn,"SELECT name FROM godown WHERE code='$godown'")); ?>
                &nbsp;|&nbsp; Godown: <?php echo htmlspecialchars($gn['name'] ?? ''); ?>
                <?php endif; ?>
            </div>
        </div>
        <button onclick="window.print()" style="background:#2563eb;color:#fff;border:none;border-radius:6px;padding:7px 16px;font-size:12px;cursor:pointer;"><i class="fa fa-print"></i> Print</button>
    </div>

<?php
if ($dtype == '1') {
    $sql = "SELECT d.vouchno, d.vouchdt, d.remarks, g.name AS godownname,
                   COALESCE(SUM(dd.qty),0) AS totqty
            FROM `damage` d
            LEFT JOIN `damagedtl` dd ON dd.vouchno = d.vouchno
            LEFT JOIN `product` p ON p.id = dd.product
            LEFT JOIN `godown` g ON g.code = d.godown
            WHERE d.vouchdt >= '$fdateIso' AND d.vouchdt <= '$tdateIso' $godowncond $searchcond
            GROUP BY d.vouchno
            ORDER BY d.vouchdt ASC, d.vouchno ASC";
    $res = mysqli_query($conn, $sql) or die(mysqli_error($conn));
    $rows = [];
    while ($r = mysqli_fetch_assoc($res)) $rows[] = $r;

    if (!$rows) {
        echo '<div class="no-data"><i class="fa fa-box-open" style="font-size:34px;display:block;margin-bottom:10px;color:#cbd5e1;"></i>No damage entries found for the selected period.</div>';
    } else {
        $totQty = 0;
        echo '<table class="rpt-tbl"><thead><tr>
            <th>#</th><th>Voucher</th><th>Date</th><th>Godown</th><th>Remarks</th><th class="num">Total Qty</th>
        </tr></thead><tbody>';
        $i = 0;
        foreach ($rows as $r) {
            $i++;
            echo '<tr>
                <td style="color:#94a3b8;font-size:11px;">'.$i.'</td>
                <td style="font-weight:600;color:#475569;">DMG#'.(int)$r['vouchno'].'</td>
                <td>'.($r['vouchdt']&&$r['vouchdt']!='0000-00-00'?date('d-m-Y',strtotime($r['vouchdt'])):'').'</td>
                <td>'.htmlspecialchars($r['godownname'] ?: '—').'</td>
                <td>'.htmlspecialchars($r['remarks'] ?: '').'</td>
                <td class="num neg" style="font-weight:700;">'.pf($r['totqty']).'</td>
            </tr>';
            $totQty += (float)$r['totqty'];
        }
        echo '</tbody><tfoot><tr>
            <td colspan="5" style="text-align:right;">Total</td>
            <td>'.pf($totQty).'</td>
        </tr></tfoot></table>';
    }

} else {
    $sql = "SELECT d.vouchno, d.vouchdt, d.remarks, g.name AS godownname, dd.qty, p.name AS prodname
            FROM `damage` d
            JOIN `damagedtl` dd ON dd.vouchno = d.vouchno
            LEFT JOIN `product` p ON p.id = dd.product
            LEFT JOIN `godown` g ON g.code = d.godown
            WHERE d.vouchdt >= '$fdateIso' AND d.vouchdt <= '$tdateIso' $godowncond $searchcond
            ORDER BY d.vouchdt ASC, d.vouchno ASC, dd.srl ASC";
    $res = mysqli_query($conn, $sql) or die(mysqli_error($conn));
    $rows = [];
    while ($r = mysqli_fetch_assoc($res)) $rows[] = $r;

    if (!$rows) {
        echo '<div class="no-data"><i class="fa fa-box-open" style="font-size:34px;display:block;margin-bottom:10px;color:#cbd5e1;"></i>No damage entries found for the selected period.</div>';
    } else {
        $totQty = 0;
        echo '<table class="rpt-tbl"><thead><tr>
            <th>#</th><th>Date</th><th>Voucher</th><th>Godown</th><th>Product</th><th>Remarks</th><th class="num">Qty</th>
        </tr></thead><tbody>';
        $i = 0;
        foreach ($rows as $r) {
            $i++;
            echo '<tr>
                <td style="color:#94a3b8;font-size:11px;">'.$i.'</td>
                <td>'.($r['vouchdt']&&$r['vouchdt']!='0000-00-00'?date('d-m-Y',strtotime($r['vouchdt'])):'').'</td>
                <td style="font-weight:600;color:#475569;">DMG#'.(int)$r['vouchno'].'</td>
                <td>'.htmlspecialchars($r['godownname'] ?: '—').'</td>
                <td>'.htmlspecialchars($r['prodname'] ?: '').'</td>
                <td>'.htmlspecialchars($r['remarks'] ?: '').'</td>
                <td class="num neg">'.pf($r['qty']).'</td>
            </tr>';
            $totQty += (float)$r['qty'];
        }
        echo '</tbody><tfoot><tr>
            <td colspan="6" style="text-align:right;">Total</td>
            <td>'.pf($totQty).'</td>
        </tr></tfoot></table>';
    }
}
?>

</div>

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