<?php
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');

try {

    if (!isset($_REQUEST['id'])) {
        header('location: ../../index.php');
        exit;
    } else {
        $id = $_REQUEST['id']; // ✅ fixed (was $_GET)
    }

    include_once('../../../classes/manager.class.php');
    // ❌ Removed PHPMailer include because it can output deprecated warning and break PDF
    // include_once('../../../classes/PHPMailer/PHPMailerAutoload.php');
    include_once('../../../fpdf/fpdfwlogo.php');

    $m = new Manager();
    $setx  = 10;
    $wPage = 195;

    $param_data = ControlConfifguration::GetConfiguration();
    define('PROJECT_NAME', $param_data->name);
    define('PROJECT_ADDRESS', $param_data->address);
    define('PROJECT_TEL', $param_data->contact);
    define('PROJECT_EMAIL', $param_data->email);
    define('PROJECT_WEBSITE', $param_data->website);
    define('PROJECT_COLOR', $param_data->color);
    define('PROJECT_DISCOUNT', $param_data->is_discount);
    define('PROJECT_TAX', $param_data->is_tax);
    define('PROJECT_NTN', $param_data->ntn);

    $invoice = Invoice::GetInvoiceSetupById($id);
    if (empty($invoice)) {
        header('location: ' . PROJECT_ADMIN_URL);
        exit;
    }

    $invoice_id = $invoice->id;
    $create_date = $invoice->create_date;
    $code = $invoice->code;
    $customer_id = $invoice->customer_id;

    // ✅ discount fields
    $discount = (float)$invoice->discount; // usually percentage
    $discount_price = isset($invoice->discount_price) ? (float)$invoice->discount_price : 0;

    $add_discount = isset($invoice->add_discount) ? (float)$invoice->add_discount : 0;
    $add_discount_price = isset($invoice->add_discount_price) ? (float)$invoice->add_discount_price : 0;

    $customer = CustomerSetup::GetCustomerSetupById($customer_id);
    $customer_name = $customer ? $customer->name : '';
    $customer_address = $customer ? $customer->location : '';
    $customer_ntn = $customer ? $customer->ntn : '';
    $customer_catid = $customer ? $customer->category_id : '';

    $customer_cat_name = '';
    if (!empty($customer_catid)) {
        $customer_category = CustomerCategorySetup::GetCustomerCategorySetupById($customer_catid);
        $customer_cat_name = $customer_category ? $customer_category->name : '';
    }

    $check_date = new DateTime('2024-09-01');
    $invoice_date = new DateTime($create_date);

    $pdf = new FPDF('P', 'mm', 'legal');
    $pdf->SetMargins(0, 15, 0);
    $pdf->SetTitle('Invoice ' . $code . ' / INVOICE');
    $pdf->AddPage();
    $pdf->Ln();

    $pdf->SetFont('Arial', 'B', 16);
    $pdf->Cell(0, 8, 'INVOICE', 0, 0, 'C');
    $pdf->Ln();
    $pdf->SetFont('Arial', 'B', 15);

    if ($invoice_date > $check_date && strpos($customer_name, 'IMTIAZ GROUP') === false) {
        $pdf->SetFont('Arial', 'B', 18);
        $pdf->Ln(4);
        $pdf->Cell(0, 6, 'The Adam Company', 0, 0, 'C');
        $pdf->Ln();
        $pdf->Ln();
    }

    $pdf->SetX($setx);
    $pdf->SetFont('Arial', 'B', 11);
    $pdf->Cell(25, 4, 'Invoice No. : ', 0, 0, '');
    $pdf->Cell(15, 4, $code, 'B', 0, 'C');
    $pdf->Cell(120, 4, '', '');
    $pdf->Cell(15, 4, 'Dated : ', 0, 0, '');
    $pdf->Cell(19, 4, date('d-m-Y', strtotime($create_date)), 'B', 0, 'C');

    if (!empty($customer_ntn)) {
        $pdf->Ln();
        $pdf->Ln();
        $pdf->SetX($setx);
        $pdf->SetFont('Arial', 'B', 11);
        $pdf->Cell(175, 4, $customer_cat_name . ' NTN : ', 0, 0, '');
        $pdf->Cell(20, 4, $customer_ntn, 'B', 0, 'R');
        $pdf->Ln();
        $pdf->Ln();
        $pdf->SetX($setx);
        $pdf->Cell(175, 4, PROJECT_NAME . " NTN : ", 0, 0, '');
        $pdf->Cell(20, 4, PROJECT_NTN, 'B', 0, 'R');
    }

    $pdf->Ln();
    $pdf->Ln();
    $pdf->SetX($setx);
    $pdf->SetFont('Arial', 'B', 12);
    $pdf->Cell(16, 5, 'Name : ', 0, 0, '');
    $pdf->Cell(179, 5, $customer_name . ' - ' . $customer_address, 'B', 0, '');
    $pdf->Ln();
    $pdf->Ln();
    $pdf->SetX($setx);
    $pdf->SetFont('Arial', 'B', 10);

    // ✅ Header changes only label; actual discount will appear in totals
    $header = array('S.No.', 'PARTICULARS', 'WEIGHT', 'CARTON', 'QTY', 'RATE', 'AMOUNT');

    $filterProductInvoice = " WHERE invoice_id = '$invoice_id'";
    $productData = Invoice::GetInvoiceProducts($filterProductInvoice);

    function FancyTable($header, $data, $setx, $discount, $discount_price, $add_discount, $add_discount_price)
    {
        global $pdf, $customer_id, $invoice_id;

        $pdf->SetFillColor(224, 235, 255);
        $pdf->SetTextColor(0);
        $pdf->SetDrawColor(0, 0, 0);
        $pdf->SetLineWidth(.2);
        $pdf->SetFont('', 'B');

        $wr = array(13, 65, 20, 21, 20, 29, 27);

        for ($i = 0; $i < count($header); $i++) {
            $pdf->Cell($wr[$i], 9, $header[$i], 1, 0, 'C', true);
        }
        $pdf->Ln();

        $pdf->SetFillColor(224, 235, 255);
        $pdf->SetTextColor(0);
        $pdf->SetFont('Arial', '', 12);
        $fill = false;

        $count = 1;
        $totalAmount = 0;
        $totalCarton = 0;
        $totalQty = 0;

        if ($data) {
            foreach ($data as $row) {
                $productSetup = ProductSetup::GetProductSetupById($row->product_id);

                $pdf->SetX($setx);
                $pdf->Cell($wr[0], 7, $count, 'LRB', 0, 'C', $fill);
                $pdf->Cell($wr[1], 7, $productSetup ? $productSetup->name : '', 'LRB', 0, 'L', $fill);
                $pdf->Cell($wr[2], 7, ($productSetup ? ($productSetup->weight . " " . $productSetup->unit) : ''), 'LRB', 0, 'C', $fill);

                $carton = ($row->carton_piece != 0 ? number_format(($row->product_qty / $row->carton_piece), 0) : "-");
                $totalCarton += ($row->carton_piece != 0 ? (float)$carton : 0);

                $pdf->Cell($wr[3], 7, $carton, 'LRB', 0, 'C', $fill);
                $pdf->Cell($wr[4], 7, $row->product_qty, 'LRB', 0, 'C', $fill);

                $rate = (float)$row->unit_sale_price;
                $pdf->Cell($wr[5], 7, number_format($rate, 2), 'LRB', 0, 'C', $fill);

                $subTotal = ((float)$row->product_qty * $rate);
                $pdf->Cell($wr[6], 7, number_format($subTotal, 2), 'LRB', 0, 'R', $fill);

                $pdf->Ln();

                $count++;
                $totalAmount += $subTotal;
                $totalQty += (float)$row->product_qty;
                $fill = !$fill;
            }
        }

        // ================= DISCOUNT CALC =================
        // Prefer stored discount_price. If not, use percentage.
        $discAmount = 0;
        if ($discount_price > 0) {
            $discAmount = $discount_price;
        } elseif ($discount > 0) {
            $discAmount = ($totalAmount * $discount) / 100;
        }

        $addDiscAmount = 0;
        if ($add_discount_price > 0) {
            $addDiscAmount = $add_discount_price;
        } elseif ($add_discount > 0) {
            $addDiscAmount = (($totalAmount - $discAmount) * $add_discount) / 100;
        }

        $netAmount = $totalAmount - $discAmount - $addDiscAmount;
        if ($netAmount < 0) $netAmount = 0;

        // ================= TOTALS PRINT =================
        $pdf->SetX($setx);
        $pdf->SetFont('Arial', 'B', 12);

        // Total Amount
        $pdf->Cell(($wr[1] + 13), 7, "", '', 0, 'C');
        $pdf->Cell($wr[2], 7, "", '', 0, 'C');
        $pdf->Cell($wr[3], 7, '', '', 0, 'R');
        $pdf->Cell($wr[4], 7, '', '', 0, 'R');
        $pdf->Cell($wr[5], 7, 'Total Amount', 'LRB', 0, 'L', "");
        $pdf->Cell($wr[6], 7, number_format($totalAmount, 2), 'LRB', 0, 'R', "");
        $pdf->Ln();

        // Discount
        if (($discAmount + $addDiscAmount) > 0) {
            $pdf->SetX($setx);
            $pdf->Cell(($wr[1] + 13), 7, "", '', 0, 'C');
            $pdf->Cell($wr[2], 7, "", '', 0, 'C');
            $pdf->Cell($wr[3], 7, '', '', 0, 'R');
            $pdf->Cell($wr[4], 7, '', '', 0, 'R');
            $pdf->Cell($wr[5], 7, 'Discount', 'LRB', 0, 'L', "");
            $pdf->Cell($wr[6], 7, number_format(($discAmount + $addDiscAmount), 2), 'LRB', 0, 'R', "");
            $pdf->Ln();

            // Net Total
            $pdf->SetX($setx);
            $pdf->Cell(($wr[1] + 13), 7, "", '', 0, 'C');
            $pdf->Cell($wr[2], 7, "", '', 0, 'C');
            $pdf->Cell($wr[3], 7, '', '', 0, 'R');
            $pdf->Cell($wr[4], 7, '', '', 0, 'R');
            $pdf->Cell($wr[5], 7, 'Net Total', 'LRB', 0, 'L', "");
            $pdf->Cell($wr[6], 7, number_format($netAmount, 2), 'LRB', 0, 'R', "");
            $pdf->Ln();
        }

        // ================= SIGNATURE =================
        $pdf->Ln();
        $pdf->SetX($setx);
        $pdf->SetFont('Arial', '', 9);
        $pdf->Cell($wr[1], 7, "Signature's", 'T', 0, 'C');
    }

    FancyTable(
        $header,
        $productData,
        $setx,
        $discount,
        $discount_price,
        $add_discount,
        $add_discount_price
    );

    $pdf->Ln(8);

    $notes = [
        'For Purchase Orders Please contact at +92 328 8954957'
    ];

    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetFillColor(224, 235, 240);
    $pdf->SetX($setx);
    $pdf->Cell($wPage, 7, 'Note:', 1, 1, 'L', true);

    $noteText = '';
    foreach ($notes as $i => $line) {
        $noteText .= ($i + 1) . '. ' . $line . "\n";
    }

    $pdf->SetFont('Arial', '', 10);
    $pdf->SetX($setx);
    $pdf->MultiCell($wPage, 6, $noteText, 1, 'L');

    if (ob_get_length()) { ob_end_clean(); }
    $pdf->Output();
    exit;

} catch (Exception $e) {
    if (ob_get_length()) { ob_end_clean(); }
    echo $e->getMessage();
}
?>
