<?php

require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

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

ini_set('display_errors', 1);
error_reporting(E_ERROR);

$success = false;

$usertype = $_SESSION["usertype_" . $dbname];
$ztit = $_SESSION["tit_" . $dbname];

$maindb = 'shipment';
$trandb = 'shiptran';

$file = 'shipment.php';

$keyfld = "vouchno";

$destination = $_REQUEST["destination"];
$rangeFrom = $_REQUEST["rangeFrom"];
$rangeTo = $_REQUEST["rangeTo"];

// Map fields to database columns (same as filtering)
$fields = [
    1 => 'a.vouchno',
    2 => 'b.name',
    3 => 'a.supplier',
    4 => 'a.marka',
    5 => 'a.containerno',
    6 => 'a.saildate',
    7 => 'a.destination',
    8 => 'a.estimdate',
    9 => 'a.delvdate'
];

// 1️⃣ Filter condition
$searchTerm = $_REQUEST["ssearch"];
$operator = $_REQUEST["soperator"];
$sfield = $_REQUEST["sfield"];

$field = $fields[$sfield] ?? 'a.vouchno';

$cond = "";
if ($sfield == 1) {
    $normalized = str_replace("GC-", "", strtoupper($searchTerm));
    $cond = ($operator == "=") ? "AND $field = '$normalized'" : "AND $field LIKE '%$normalized%'";
} else {
    $cond = ($operator == "=") ? "AND $field = '$searchTerm'" : "AND $field LIKE '%$searchTerm%'";
}

// 2️⃣ Sorting
$sortBy = $_REQUEST['sortBy'];
$sortField = $fields[$sortBy] ?? 'a.vouchdt';
$orderAs = strtolower($_REQUEST['orderAs'] ?? 'asc');
$ordcond = ($orderAs === 'desc') ? 'DESC' : 'ASC';
$sortcond = "ORDER BY $sortField $ordcond";


$query = "SELECT a.*,DATE_FORMAT(a.`vouchdt`, '%d-%m-%Y') as mydt,b.name as custname
                FROM `$maindb` a
                LEFT JOIN accmast b ON a.customer = b.accode
                WHERE a.destination='$destination' AND delvdate = '0000-00-00' 
                $cond $sortcond LIMIT $rangeFrom, $rangeTo";

$result = mysqli_query($conn, $query) or die(mysqli_error($conn));

$rows = array();
$ctr = 0;
while ($r = mysqli_fetch_assoc($result)) {

    // if ($r['sector'] == "New DELHI") {
    //     $colr = "style='color:red'";
    // } else {
    $colr = "";
    // }

    $bgcolor = "";
    // if (($r['gamca'] != '0000-00-00') && ($r['passport'] != '')) {
    //     $bgcolor = "background-color:#cae9ff";
    // } elseif (($r['stampdate'] != '0000-00-00'))  {
    //     $bgcolor = "background-color:#57cc99";
    // } elseif ($r['flight_date'] != '0000-00-00') {
    //     $bgcolor = "background-color:#ff9671 ";
    // } elseif (($r['visa_cancel'] != '0000-00-00')) {
    //     if ($r['mofa_date'] != '0000-00-00') {
    //         $bgcolor = "background-color:#f49cbb";
    //     } else {
    //         $bgcolor = "background-color:#5fa8d3";
    //     }
    // }   else {
    //     $bgcolor = "background-color:#ffffff ";
    // }


    $ctr++;

    $rows[] = [
        'success' => true,
        'ctr' => $ctr,
        'vouchno' => "GC-" . $r['vouchno'],
        'vouchdt' => $r['mydt'],
        'customer' => $r['custname'],
        'nocart' => $r['nocart'],
        'supplier' => $r['supplier'],
        'description' => $r['description'],
        'pcs' => $r['pcs'],
        'unit' => $r['unit'],
        'marka' => $r['marka'],
        'totcbm' => $r['totcbm'],
        'weight' => $r['weight'],
        'containerno' => $r['containerno'],
        'saildate' => format_date($r['saildate']),
        'origin' => $r['origin'],
        'estimdate' => format_date($r['estimdate']),
        'delvdate' => format_date($r['delvdate']),
        'mobile' => $r['mobile'],
        'colr' => $colr,
        'usertype' => $usertype,
        'bgcolr' => $bgcolor,
        'action' => "$file?mode=edit&vouchno=$r[vouchno]",
    ];
}
//browse($rows);
header("Content-type: application\json");
echo json_encode($rows);
