<?php

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

mysqli_query($conn, "SET NAMES 'utf8'");
mysqli_query($conn, 'SET CHARACTER SET utf8');

//browse('Work In Progress. Please wait');

$formname = 'Order / Estimate';
$maindb = 'salemain';
$trandb = 'saletran';
$file = '';
$source = "SL";
$zdb = $_SESSION["zdbyear_" . $dbname];
$zroot = $_SESSION["zdir"];
mysqli_select_db($conn, $zdb);
$mht = 'height:20px;';

$admin = $_SESSION["admin_" . $dbname];
$vouchno = $_REQUEST["vouchno"];

$instid = $_SESSION["instid"];
$accstkn = $_SESSION["accstkn"];

$mainqry = mysqli_query($conn, "SELECT *, DATE_FORMAT(`vouchdt`, '%d-%m-%Y') AS mydt FROM `$maindb` WHERE vouchno='$vouchno'") or die(mysqli_error($conn));
$getmdata = mysqli_fetch_array($mainqry);
$vouchdt = $getmdata['mydt'];
$advance = $getmdata['totadv'];
$cashcred = $getmdata['paidby'];
$cashvouch = $getmdata['cashvouch'];

$zroot = $_SESSION["zdir"];

$zcomp = $_SESSION["comp_" . $dbname];

$getcomp = mysqli_query($conn, "SELECT * FROM $zroot.`company` WHERE `code`= '$zcomp' ") or die(mysqli_error($conn));
$comp = mysqli_fetch_array($getcomp);

$getpaccode = mysqli_query($conn, "SELECT * FROM `accmast` WHERE `accode`= '$getmdata[party]'") or die(mysqli_error($conn));
$cust = mysqli_fetch_array($getpaccode);

// $gettransp = mysqli_query($conn, "SELECT `code`,`name` FROM `transport` WHERE `code`= '$getmdata[transporter]'") or die(mysqli_error($conn));
// $ltrans = mysqli_fetch_array($gettransp);
$accode = $cust['accode'];
$add1 = $cust['add1'];
$mobile = $cust['mobile'];
$add2 = $cust['add2'];
$add3 = $cust['add3'];
$city = $cust['city'];
$pin = $cust['pin'];
$paytype = $getmdata['paidby'];

$openbal = $cust['openbal'];
$dc = $cust['dc'];

if ($dc == "D") {
    $mopbal = abs($openbal) * -1;
} else {
    $mopbal = abs($openbal);
}

mysqli_query($conn, "drop temporary table if exists baldbf ") or die(mysqli_error($conn));
mysqli_query($conn, "create temporary table baldbf 
                            select * from actran WHERE `accode`= '$accode'") or die(mysqli_error($conn));

mysqli_query($conn, "delete from baldbf WHERE `source`= 'SL' and vouchno >= '$vouchno' ") or die(mysqli_error($conn));
mysqli_query($conn, "delete from baldbf WHERE `source`= 'CR' and vouchno = '$cashvouch' ") or die(mysqli_error($conn));

$getbal = mysqli_query($conn, "SELECT sum(amount) as amt1 FROM `baldbf` ") or die(mysqli_error($conn));
$fetbal = mysqli_fetch_array($getbal);
$topen1 = $fetbal['amt1'];
$topen = $topen1;

$prevbal1 = $mopbal + $topen;

$prevbal = $prevbal1 * -1;

if ($paytype == 'C') {
    $actprev = 0;
} else {
    $actprev = $prevbal;
}


require('library/fpdf/fpdf.php');

class PDF extends FPDF {

    function Header() {

        // Outer Border
    }
}

$pdf = new PDF();
$pdf->AddPage();
$pdf->SetAutoPageBreak(false);

// =========================
// SAMPLE DATA
// =========================


if ($paytype == "C") {
    $paidby = 'CASH';
} else {
    $paidby = 'CREDIT';
}

$pdf->SetDrawColor(80, 80, 80);
$pdf->Rect(15, 10, 180, 280);

// Company Name
$pdf->SetFont('Times', 'B', 22);
$pdf->Cell(0, 12, "$comp[compname]", 0, 1, 'C');

// Title
$pdf->SetFont('Arial', 'BU', 12);
$pdf->Cell(0, 0, 'Order / Estimate', 0, 1, 'C');

$pdf->Ln(12);
// =========================
// CUSTOMER DETAILS
// =========================
$pdf->SetFont('Arial', 'B', 11);
$pdf->SetXY(18, 45);
$pdf->Cell(60, 5, 'Customer Details', 0, 1);

$pdf->SetFont('Arial', '', 10);
$pdf->SetX(18);
$pdf->Cell(80, 5, $cust['name'], 0, 1);
$pdf->Ln(8);

$pdf->SetX(18);
$pdf->Cell(80, 5, $city, 0, 0);
$pdf->SetFont('Arial', 'B', 11);
$pdf->Cell(48, 5, 'No. :', 0, 0, 'R');
$pdf->SetFont('Arial', '', 11);
$pdf->Cell(10, 5, $getmdata['invno'], 0, 1);

$pdf->SetX(18);
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(80, 5, 'Transporter : ' . $ltrans['name'], 0, 0);
$pdf->SetFont('Arial', 'B', 11);
$pdf->Cell(48, 5, 'Date:', 0, 0, 'R');
$pdf->SetFont('Arial', '', 11);
$pdf->Cell(25, 5, $getmdata['mydt'], 0, 1);
$pdf->Ln(2);

$pdf->SetFont('Arial', 'B', 11);
$pdf->SetX(126);
$pdf->Cell(20, 5, 'Paid By :', 0, 0, 'R');

$pdf->SetFont('Arial', '', 10);
$pdf->Cell(20, 5, $paidby, 0, 0, 'L');
$pdf->Ln(7);

// =========================
// TABLE HEADER
// =========================
$startY = 83;

// $pdf->SetXY(18, $startY);
$pdf->SetFont('Arial', 'B', 10);

$pdf->Cell(7, 6, '', 0, 0, 'C');
$pdf->Cell(12, 6, 'Sr', 1, 0, 'C');
$pdf->Cell(95, 6, 'Item', 1, 0, 'C');
$pdf->Cell(18, 6, 'Qty.', 1, 0, 'C');
$pdf->Cell(22, 6, 'Rate', 1, 0, 'C');
$pdf->Cell(25, 6, 'Amount', 1, 0, 'C');
$pdf->Ln();

// =========================
// TABLE ROWS
// =========================
$pdf->SetFont('Arial', '', 9);

$rowHeight = 8;
$totalRows = 16;
$currentY = $startY + 6;
// $pdf->SetX(18);

$tranpart = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE `vouchno`='$getmdata[vouchno]' order by srno") or die(mysqli_error($conn));
$ctab = 0;
$grqty = 0;
while ($row = mysqli_fetch_array($tranpart)) {
    $getbrand = mysqli_query($conn, "SELECT * FROM `product` WHERE code = '$row[itemcode]'") or die(mysqli_error($conn));
    $getb = mysqli_fetch_array($getbrand);

    $pdf->Cell(7, $rowHeight, '', 0, 0, 'C');
    $pdf->Cell(12, $rowHeight, $row['srno'], 1, 0, 'C');
    $pdf->Cell(95, $rowHeight, $getb['name'], 1, 0, 'L');
    $pdf->Cell(18, $rowHeight, $row['qty'], 1, 0, 'R');
    $pdf->Cell(22, $rowHeight, $row['rate'], 1, 0, 'R');
    $pdf->Cell(25, $rowHeight, $row['amount'], 1, 0, 'R');
    $pdf->Ln();

    $currentY += $rowHeight;

    $totalqty += $row['qty'];
    $totamt += $row['amount'];
}

if ($ctab < 14) {
    for ($i = $ctab; $i <= 14; $i++) {
        $ctab = $ctab + 1;

        $pdf->Cell(7, $rowHeight, '', 0, 0, 'C');
        $pdf->Cell(12, $rowHeight, "", 1, 0, 'C');
        $pdf->Cell(95, $rowHeight, "", 1, 0, 'L');
        $pdf->Cell(18, $rowHeight, "", 1, 0, 'R');
        $pdf->Cell(22, $rowHeight, "", 1, 0, 'R');
        $pdf->Cell(25, $rowHeight, "", 1, 0, 'R');
        $pdf->Ln();
    }
}

// =========================
// TOTAL SECTION
// =========================
$pdf->SetFont('Arial', '', 10);
// $pdf->SetXY(120, 218);
$pdf->Cell(100, 5, "", 0, 0, 'L');
$pdf->Cell(14, 5, 'Qty. ', 0, 0, 'R');
$pdf->Cell(18, 5, $totalqty, 0, 0, 'R');

$pdf->Cell(23, 5, 'Total', 0, 0, 'R');
$pdf->Cell(25, 5, $totamt, 0, 0, 'R');
$pdf->Ln();

$pdf->SetFont('Arial', '', 11);
$pdf->Cell(122, 5, "", 0, 0, 'L');
$pdf->Cell(33, 5, 'Less Discount    ' . $getmdata['ldiscperc'] . ' %', 0, 0, 'R');
$pdf->Cell(25, 5, $getmdata['totdisc'], 0, 0, 'R');
$pdf->Ln();

$pdf->SetFont('Arial', '', 11);
$pdf->Cell(132, 5, "", 0, 0, 'L');
$pdf->Cell(23, 5, 'Add Transport', 0, 0, 'R');
$pdf->Cell(25, 5, $getmdata['addpack'], 0, 0, 'R');
$pdf->Ln();

$pdf->SetFont('Arial', '', 11);
$pdf->Cell(132, 5, "", 0, 0, 'L');
$pdf->Cell(23, 5, 'Add GT', 0, 0, 'R');
$pdf->Cell(25, 5, $getmdata['addgst'], 0, 0, 'R');
$pdf->Ln();

$pdf->SetFont('Arial', 'B', 9);
$pdf->Cell(5, 5, "", 0, 0, 'L');
$pdf->Cell(127, 5, "Rupees" . rsword($getmdata['billamt']) . " Only", 0, 0, 'L');
$pdf->SetFont('Arial', 'B', 11);
$pdf->Cell(23, 5, 'Bill Amount', 0, 0, 'R');
$pdf->Cell(25, 5, $getmdata['billamt'], 0, 0, 'R');
$pdf->Ln();

// =========================
// FOOTER DETAILS
// =========================

$pdf->SetFont('Arial', '', 10);
$pdf->Cell(5, 5, '', 0, 0, 'L');
$pdf->Cell(18, 5, 'Narration', 0, 0, 'L');
$pdf->Cell(2, 5, ':', 0, 0, 'L');
$pdf->Cell(107, 5, $getmdata['rem1'], 0, 0, 'L');

if ($actprev != 0) {
    $pdf->Cell(23, 5, 'Previous Bal.', 0, 0, 'R');
    $pdf->Cell(25, 5, $actprev, 0, 0, 'R');
} else {
    $pdf->Cell(48, 5, "", 0, 0, 'R');
}

$pdf->Ln();

$billamt = $getmdata['billamt'];
if ($paytype == "C") {
    $actprev = 0;
}
$totbal = $billamt - $advance + $actprev;

$pdf->SetFont('Arial', '', 10);
$pdf->Cell(5, 5, '', 0, 0, 'L');
$pdf->Cell(18, 5, '', 0, 0, 'L');
$pdf->Cell(2, 5, '', 0, 0, 'L');
$pdf->Cell(107, 5, $getmdata['rem2'], 0, 0, 'L');

if ($paytype != "C") {
    if ($getmdata['totadv'] > 0) {
        $pdf->Cell(23, 5, 'Advance', 0, 0, 'R');
        $pdf->Cell(25, 5, $getmdata['totadv'], 0, 0, 'R');
    } else {
        $pdf->Cell(48, 5, "", 0, 0, 'R');
    }
}

$pdf->Ln();

$pdf->SetFont('Arial', '', 10);
$pdf->Cell(5, 5, '', 0, 0, 'L');
$pdf->Cell(18, 5, 'Packed By', 0, 0, 'L');
$pdf->Cell(2, 5, ':', 0, 0, 'L');
$pdf->Cell(107, 5, $getmdata['packby'], 0, 0, 'L');

if ($paytype != "C") {
    $pdf->Cell(23, 5, 'Balance', 0, 0, 'R');
    $pdf->Cell(25, 5, $totbal, 0, 0, 'R');
}
$pdf->Ln(20);

// Authorized Signatory
$pdf->Cell(150, 5, "", 0, 0, 'L');
$pdf->Cell(30, 5, 'Authorized Signatory', 0, 1, 'R');
$pdf->Ln();

ob_end_clean();

// =========================
// OUTPUT
// =========================

$para = $_REQUEST["para"];

if ($para == "") {
    $pdf->Output("BILL-" . $getmdata['vouchno'] . ".pdf", "I");
} else {
    $myyear = $_SESSION[$myyear];
    $nomFacture = $_SERVER['DOCUMENT_ROOT'] . "/admin/billk/$myyear/" . $getmdata['vouchno'] . ".pdf";
    clearstatcache();

    $urlsend = "https://mysoft365.com/sisgstnew/admin/billk/$myyear/" . $getmdata['vouchno'] . ".pdf?v=" . time();

// Delete old PDF if it exists
    if (file_exists($nomFacture)) {
        @unlink($nomFacture);
    }

// Generate new PDF
    $pdf->Output($nomFacture, "F");

// Verify PDF created
    if (!file_exists($nomFacture)) {
        die("PDF generation failed.");
    }

// ======================
// WHATSAPP SEND
// ======================

    $filevoucher = "BILL-" . $getmdata['vouchno'];
    $filename = "BILL-" . $getmdata['vouchno'] . ".pdf";

    $mobileno = trim($mobile);

// TEST NUMBER
// $mobileno = '9082336408';

    if (!empty($mobileno)) {

        // Show message to user immediately
        echo "
    <script>
        alert('Message Send to Customer');
        setTimeout(function() {
            window.close();
        }, 1000);
    </script>";

        // Flush browser response
        ignore_user_abort(true);
        set_time_limit(0);

        if (function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        } else {
            @ob_end_flush();
            flush();
        }

        // ======================
        // API URL
        // ======================

        $apiUrl = "https://web.secureleads.in/api/send?" . http_build_query([
                    'number' => '91' . $mobileno,
                    'type' => 'media',
                    'message' => $filevoucher,
                    'media_url' => $urlsend,
                    'filename' => $filename,
                    'instance_id' => $instid,
                    'access_token' => $accstkn
        ]);

        // Log URL for debugging
        file_put_contents(
                "/tmp/whatsapp_url.log",
                date('Y-m-d H:i:s') . " => " . $apiUrl . PHP_EOL,
                FILE_APPEND
        );

        // Response log file
        $logFile = "/tmp/whatsapp_send_Bill_" . $getmdata['vouchno'] . ".log";

        // Background CURL
        $cmd = sprintf(
                "curl -s -X POST %s -H %s > %s 2>&1 &",
                escapeshellarg($apiUrl),
                escapeshellarg("Cookie: stackpost_session=m1ip03t51dk5rlgaa5blakqmva57k3nd"),
                escapeshellarg($logFile)
        );

        exec($cmd);
    } else {
        echo "<script>     
                   alert('No. Mobile no. Found');                
                   window.close();              
                   </script>";
    }
}