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

$formname = 'Salesman Performance Report';

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

// ── Inputs from filter form ──────────────────────────────────────────────
$salesman = isset($_POST['salesman']) ? (int)$_POST['salesman'] : 0;
$dtype    = isset($_POST['dtype'])    ? trim($_POST['dtype'])   : '1';   // 1=Summary, 2=Detail

function d2sql($d) {
    if ($d != '' && preg_match('/^(\d{2})-(\d{2})-(\d{4})$/', $d, $m)) {
        return $m[3] . '-' . $m[2] . '-' . $m[1];
    }
    return '';
}
$mfrmdate = d2sql(isset($_POST['fdate']) ? trim($_POST['fdate']) : '');
$mtodate  = d2sql(isset($_POST['tdate']) ? trim($_POST['tdate']) : '');

if ($mfrmdate == '') {
    browse("From Date Cannot Be Empty");
    header("refresh:1; url=salesmanperf.php");
    exit;
}
if ($mtodate == '') {
    browse("To Date Cannot Be Empty");
    header("refresh:1; url=salesmanperf.php");
    exit;
}

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

// ── Combined Sale Invoice + Sale GST Invoice voucher pool, tagged by type ──
$unionSql = "SELECT 'SAL' AS vtype, vouchno, vouchdt, salesman, customer, totamt AS amt FROM `sale`
                WHERE `vouchdt`>='$mfrmdate' AND `vouchdt`<='$mtodate'
             UNION ALL
             SELECT 'SGST' AS vtype, vouchno, vouchdt, salesman, customer, totamt AS amt FROM `salegst`
                WHERE `vouchdt`>='$mfrmdate' AND `vouchdt`<='$mtodate'";

$smCond = ($salesman > 0) ? " WHERE t.`salesman`='$salesman'" : " WHERE t.`salesman`>0";

// ── Per-salesman summary ───────────────────────────────────────────────────
$getmain = mysqli_query($conn, "SELECT t.salesman, a.`name` AS salesmanname,
        SUM(CASE WHEN t.vtype='SAL'  THEN 1 ELSE 0 END) AS salecnt,
        SUM(CASE WHEN t.vtype='SAL'  THEN t.amt ELSE 0 END) AS saleamt,
        SUM(CASE WHEN t.vtype='SGST' THEN 1 ELSE 0 END) AS sgstcnt,
        SUM(CASE WHEN t.vtype='SGST' THEN t.amt ELSE 0 END) AS sgstamt,
        COUNT(*) AS totcnt, SUM(t.amt) AS totamt
    FROM ($unionSql) t
    LEFT JOIN `accmast` a ON a.accode = t.salesman
    $smCond
    GROUP BY t.salesman
    ORDER BY totamt DESC") or die(mysqli_error($conn));

if (isset($_POST["view"])) {

    include("includes/linkshead.php");
    $mfdt = date('d-m-Y', strtotime($mfrmdate));
    $mtdt = date('d-m-Y', strtotime($mtodate));
    ?>
<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; }
    .sim-card-header .sub { font-size:11.5px; color:#94a3b8; margin-top:2px; }

    .sim-body { padding:18px 20px; }

    .btn { padding:8px 16px; border:none; border-radius:6px; font-size:12.5px; font-weight:600; cursor:pointer; display:inline-flex; align-items:center; gap:6px; text-decoration:none; }
    .btn-export { background:#16a34a; color:#fff; }
    .btn-export:hover { background:#15803d; }
    .btn-print { background:#4a5759; color:#fff; }
    .btn-print:hover { background:#374043; }

    table.reg { width:100%; border-collapse:collapse; font-size:12px; }
    table.reg th {
        background:#f8fafc; color:#374151; font-weight:700; font-size:11px;
        text-transform:uppercase; letter-spacing:.04em; padding:8px 10px;
        border-bottom:2px solid #e2e8f0; text-align:left; white-space:nowrap;
    }
    table.reg th.num { text-align:right; }
    table.reg td { padding:6px 10px; border-bottom:1px solid #f1f5f9; white-space:nowrap; }
    table.reg td.num { text-align:right; }
    table.reg tbody tr.mainrow { font-weight:600; }
    table.reg tfoot td { font-weight:700; background:#f8fafc; border-top:2px solid #e2e8f0; }

    .dtype-sub th { background:#e2e8f0; }
    .reg-wrap { overflow:auto; }

    @media print {
        body { background:#fff; padding:0; }
        .no-print { display:none !important; }
        .sim-card { box-shadow:none; border-radius:0; }
    }
</style>
</head>
<body>
<div class="sim-card">
    <div class="sim-card-header">
        <div>
            <h2><i class="fa fa-user-tie" style="color:#3b82f6;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?> (<?php echo $dtype=='2' ? 'Detail' : 'Summary'; ?>)</h2>
            <div class="sub"><?php echo $mfdt; ?> to <?php echo $mtdt; ?></div>
        </div>
        <div class="no-print" style="display:flex;gap:8px;">
            <button type="button" class="btn btn-print" onclick="window.print()"><i class="fa fa-print"></i> Print</button>
            <button onclick="if(window.parent&&window.parent!==window){window.parent.document.getElementById('rptframe').src='about:blank';}else{window.close();}" style="padding:8px 22px;background:#f1f5f9;color:#374151;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;margin-left:8px;"><i class="fa fa-arrow-left"></i> Go Back</button>
            <form method="POST" style="margin:0;">
                <?php foreach ($_POST as $k => $v) { if ($k != 'view') echo '<input type="hidden" name="' . htmlspecialchars($k) . '" value="' . htmlspecialchars($v) . '">'; } ?>
                <button type="submit" name="excel" value="1" class="btn btn-export"><i class="fa fa-file-csv"></i> Export CSV</button>
            </form>
        </div>
    </div>

    <div class="sim-body">
    <div class="reg-wrap">
    <table class="reg">
        <thead>
            <tr>
                <th>Sr</th>
                <th>Salesman</th>
                <th class="num">Sale Inv</th>
                <th class="num">Sale Amount</th>
                <th class="num">GST Inv</th>
                <th class="num">GST Amount</th>
                <th class="num">Total Inv</th>
                <th class="num">Total Amount</th>
                <th class="num">Share %</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $ctr = 0;
            $tSaleCnt = $tSaleAmt = $tSgstCnt = $tSgstAmt = $tTotCnt = 0;
            $tTotAmt  = 0.0;
            $rows = [];
            while ($m = mysqli_fetch_array($getmain)) { $rows[] = $m; $tTotAmt += (float)$m['totamt']; }
            $grandAmt = $tTotAmt;

            foreach ($rows as $m) {
                $ctr++;
                $share = $grandAmt > 0 ? ((float)$m['totamt'] / $grandAmt * 100) : 0;
                echo "<tr class='mainrow'>";
                echo "<td style='text-align:center;'>$ctr</td>";
                echo "<td>" . htmlspecialchars($m['salesmanname'] ?? 'Unassigned') . "</td>";
                echo "<td class='num'>" . (int)$m['salecnt'] . "</td>";
                echo "<td class='num'>" . pf($m['saleamt']) . "</td>";
                echo "<td class='num'>" . (int)$m['sgstcnt'] . "</td>";
                echo "<td class='num'>" . pf($m['sgstamt']) . "</td>";
                echo "<td class='num'>" . (int)$m['totcnt'] . "</td>";
                echo "<td class='num' style='font-weight:700;'>" . pf($m['totamt']) . "</td>";
                echo "<td class='num'>" . number_format($share, 1) . "%</td>";
                echo "</tr>";

                $tSaleCnt += (int)$m['salecnt'];
                $tSaleAmt += (float)$m['saleamt'];
                $tSgstCnt += (int)$m['sgstcnt'];
                $tSgstAmt += (float)$m['sgstamt'];
                $tTotCnt  += (int)$m['totcnt'];

                if ($dtype == '2') {
                    $vch = mysqli_query($conn, "SELECT t.vtype, t.vouchno, t.vouchdt, c.`name` AS customername, t.amt
                            FROM ($unionSql) t LEFT JOIN `accmast` c ON c.accode = t.customer
                            WHERE t.salesman='" . (int)$m['salesman'] . "'
                            ORDER BY t.vouchdt ASC, t.vouchno ASC") or die(mysqli_error($conn));

                    echo "<tr><td colspan='9' style='padding:4px 10px 10px;background:#fafbfc;'>";
                    echo "<table style='width:100%;border-collapse:collapse;font-size:11.5px;' class='dtype-sub'>";
                    echo "<tr>
                            <th style='width:6%;padding:6px;'>Sr</th>
                            <th style='padding:6px;'>Type</th>
                            <th style='padding:6px;'>Voucher No</th>
                            <th style='padding:6px;'>Date</th>
                            <th style='padding:6px;'>Customer</th>
                            <th style='padding:6px;text-align:right;'>Amount</th>
                          </tr>";
                    $ctr2 = 0;
                    while ($v = mysqli_fetch_array($vch)) {
                        $ctr2++;
                        $vdt = $v['vouchdt'] && $v['vouchdt'] != '0000-00-00' ? date('d-m-Y', strtotime($v['vouchdt'])) : '';
                        $vlabel = $v['vtype'] == 'SGST' ? 'Sale GST' : 'Sale';
                        echo "<tr>";
                        echo "<td style='text-align:center;padding:5px;'>$ctr2</td>";
                        echo "<td style='padding:5px;'>$vlabel</td>";
                        echo "<td style='padding:5px;'>" . ($v['vtype']=='SGST'?'SG#':'SAL#') . $v['vouchno'] . "</td>";
                        echo "<td style='padding:5px;'>$vdt</td>";
                        echo "<td style='padding:5px;'>" . htmlspecialchars($v['customername'] ?? '') . "</td>";
                        echo "<td class='num' style='padding:5px;'>" . pf($v['amt']) . "</td>";
                        echo "</tr>";
                    }
                    echo "</table>";
                    echo "</td></tr>";
                }
            }
            ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="2" style="text-align:right;">Grand Total (<?php echo $ctr; ?> salesmen)</td>
                <td class="num"><?php echo $tSaleCnt; ?></td>
                <td class="num"><?php echo pf($tSaleAmt); ?></td>
                <td class="num"><?php echo $tSgstCnt; ?></td>
                <td class="num"><?php echo pf($tSgstAmt); ?></td>
                <td class="num"><?php echo $tTotCnt; ?></td>
                <td class="num"><?php echo pf($tTotAmt); ?></td>
                <td class="num">100.0%</td>
            </tr>
        </tfoot>
    </table>
    </div>
    </div>
</div>

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

if (isset($_POST["excel"])) {
    $contents = '';
    $contents .= "Sr.,Salesman,Sale Inv,Sale Amount,GST Inv,GST Amount,Total Inv,Total Amount,Share %\n";

    $ctr = 0;
    $tSaleCnt = $tSaleAmt = $tSgstCnt = $tSgstAmt = $tTotCnt = 0;
    $tTotAmt  = 0.0;
    $rows = [];
    while ($m = mysqli_fetch_array($getmain)) { $rows[] = $m; $tTotAmt += (float)$m['totamt']; }
    $grandAmt = $tTotAmt;

    foreach ($rows as $m) {
        $ctr++;
        $share = $grandAmt > 0 ? ((float)$m['totamt'] / $grandAmt * 100) : 0;
        $contents .= $ctr . ",";
        $contents .= '"' . str_replace('"','""',$m['salesmanname'] ?? 'Unassigned') . '"' . ",";
        $contents .= (int)$m['salecnt'] . ",";
        $contents .= $m['saleamt'] . ",";
        $contents .= (int)$m['sgstcnt'] . ",";
        $contents .= $m['sgstamt'] . ",";
        $contents .= (int)$m['totcnt'] . ",";
        $contents .= $m['totamt'] . ",";
        $contents .= number_format($share, 1) . "\n";

        $tSaleCnt += (int)$m['salecnt'];
        $tSaleAmt += (float)$m['saleamt'];
        $tSgstCnt += (int)$m['sgstcnt'];
        $tSgstAmt += (float)$m['sgstamt'];
        $tTotCnt  += (int)$m['totcnt'];

        if ($dtype == '2') {
            $contents .= "Sr.,Type,Voucher No,Date,Customer,Amount\n";
            $vch = mysqli_query($conn, "SELECT t.vtype, t.vouchno, t.vouchdt, c.`name` AS customername, t.amt
                    FROM ($unionSql) t LEFT JOIN `accmast` c ON c.accode = t.customer
                    WHERE t.salesman='" . (int)$m['salesman'] . "'
                    ORDER BY t.vouchdt ASC, t.vouchno ASC") or die(mysqli_error($conn));
            $ctr2 = 0;
            while ($v = mysqli_fetch_array($vch)) {
                $ctr2++;
                $vdt = $v['vouchdt'] && $v['vouchdt'] != '0000-00-00' ? date('d-m-Y', strtotime($v['vouchdt'])) : '';
                $vlabel = $v['vtype'] == 'SGST' ? 'Sale GST' : 'Sale';
                $contents .= $ctr2 . ",";
                $contents .= $vlabel . ",";
                $contents .= ($v['vtype']=='SGST'?'SG#':'SAL#') . $v['vouchno'] . ",";
                $contents .= $vdt . ",";
                $contents .= '"' . str_replace('"','""',$v['customername'] ?? '') . '"' . ",";
                $contents .= $v['amt'] . "\n";
            }
        }
        $contents .= "\n";
    }

    $contents .= ",Grand Total,";
    $contents .= $tSaleCnt . ",";
    $contents .= $tSaleAmt . ",";
    $contents .= $tSgstCnt . ",";
    $contents .= $tSgstAmt . ",";
    $contents .= $tTotCnt . ",";
    $contents .= $tTotAmt . ",";
    $contents .= "100.0\n";

    $contents = strip_tags($contents);

    header('Content-Type: text/csv; charset=utf-8');
    if ($dtype == '1') {
        header("Content-Disposition: attachment; filename=" . str_replace(' ','_',$formname) . "_Summary_" . date('d-m-Y') . ".csv");
    } else {
        header("Content-Disposition: attachment; filename=" . str_replace(' ','_',$formname) . "_Detail_" . date('d-m-Y') . ".csv");
    }
    print $contents;
}
