<?php
require("../../classes/autoload.php"); // Make sure FPDF is included

$payment_res = $db->query("payments", "SELECT * FROM payments WHERE record_id = '{$_GET['record_id']}'");
$payment = $payment_res->fetch_assoc();
$invoice_res = $db->query('invoices', "SELECT * FROM invoices WHERE record_id = '{$payment['invoice_id']}'");
$invoice = $invoice_res->fetch_assoc();

$company_res = $db->query("company_info", "SELECT * FROM company_info WHERE record_id = 1");
$company = $company_res->fetch_assoc();


$client_details_res = $db->query("clients", "SELECT * FROM clients WHERE record_id = '{$invoice['client_id']}'");
$client = $client_details_res->fetch_assoc();

$invoice_list_res = $db->query("invoice_list", "SELECT * FROM invoice_list WHERE invoice_id = '{$invoice['record_id']}'");
$index = 1;

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial', '', 12);
// Logos
$pdf->Image('../../assets/logo.png', 10, 8, 30);
$pdf->Image('../../assets/logo_2.png', 170, 11, 25);

// Title
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(0, 20, 'CASH RECEIPT', 0, 1, 'C');
$pdf->Cell(0, 20, 'INVOICE : ' . $invoice['invoice_number'], 0, 1, 'C');
$pdf->Ln(10);


// Client Details
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(110, 8, $client['name'], 0, 0);
$pdf->Cell(80, 8, $company['name'], 0, 1);
$pdf->SetFont('Arial', '', 9);

$pdf->Cell(110, 8, $client['email'], 0, 0);
// $pdf->Cell(80, 8, "Reg: " . $company['reg'] . " | Vat NR: " . $company['vat'], 0, 1);
$pdf->Cell(80, 8, "TEL: " . $company['tel'], 0, 1);

$pdf->Cell(110, 8, $client['contact_person'], 0, 0);
$pdf->Cell(80, 8, "EMAIL: " . $company['email'], 0, 1);

$pdf->Cell(110, 8, $client['contact_number'], 0, 1);
$pdf->MultiCell(100, 8, $client['address']);
$pdf->Ln(6);
$pdf->SetXY(120, 64);
$pdf->MultiCell(70, 8, $company['address_line_1'] . "\n" . $company['address_line_2'] . "\n" . $company['address_line_3'] . "\n" . $company['address_line_4']);
// $pdf->Ln(11);

// $pdf->Ln(5);


// Quote Info
$pdf->Ln(5);

$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(26, 6, "DATE: ", 0, 0);
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(50, 6, $invoice['date_time_created'], 0, 1);
$pdf->Ln(3);


// Table Header
// $pdf->SetFont('Arial', 'B', 8);
// $pdf->SetFillColor(200, 200, 200);
// $pdf->Cell(20, 7, 'Amount', 1, 0, 'C', true);
// $pdf->Cell(58, 7, 'date', 1, 0, 'C', true);
// $pdf->Cell(12, 7, 'U.O.M', 1, 0, 'C', true);
// $pdf->Cell(15, 7, 'Qty', 1, 0, 'C', true);
// $pdf->Cell(15, 7, 'Size', 1, 0, 'C', true);
// $pdf->Cell(15, 7, 'Panels', 1, 0, 'C', true);
// $pdf->Cell(25, 7, 'Amount', 1, 0, 'C', true);
// $pdf->Cell(25, 7, 'Total', 1, 1, 'C', true);

// // Table Body
// $pdf->SetFont('Arial', '', 7);
$subtotal = 0;

function sa_str_to_float($str)
{
    // Remove R, spaces, and UTF-8 garbage like Â
    $str = str_replace(['R', ' ', 'Â'], '', $str);

    // If both , and . exist, assume , is thousand sep, . is decimal
    if (strpos($str, ',') !== false && strpos($str, '.') !== false) {
        $str = str_replace(',', '', $str);
    }
    // If only comma exists, assume it's decimal
    elseif (strpos($str, ',') !== false) {
        $str = str_replace(',', '.', $str);
    }

    return floatval($str);
}

foreach ($invoice_list_res as $invoice_list) {
    $stock_res = $db->query("stock", "SELECT * FROM stock WHERE record_id = '{$invoice_list['stock_id']}'");
    $stock = $stock_res->fetch_assoc();

    // Clean price string
    $price = (float) preg_replace('/[^0-9\.,]/', '', str_replace(['R', '�', 'Â', ','], '', utf8_decode($invoice_list['price'])));
    $qty = (float) $invoice_list['qty']; // make sure qty is float/int

    $total = $price * $qty;
    $subtotal += $total;

    // $pdf->Cell(20, 7, $stock['code'], 1);
    // $pdf->Cell(58, 7, $stock['name'], 1);
    // $pdf->Cell(12, 7, $stock['unit_of_measure'], 1);
    // $pdf->Cell(15, 7, $qty, 1, 0, 'C');
    // $pdf->Cell(15, 7, $invoice_list['size_m'], 1, 0, 'C');
    // $pdf->Cell(15, 7, $invoice_list['pannels'], 1, 0, 'C');
    // $pdf->Cell(25, 7, 'R ' . number_format($price, 2), 1, 0, 'L'); // use cleaned float
    // $pdf->Cell(25, 7, 'R ' . number_format($total, 2), 1, 1, 'L');
}

$credit_total = 0;
$credit_details_res = $db->query("credit_notes", "SELECT * FROM credit_notes WHERE invoice_id = {$invoice['record_id']}");
if ($credit_details_res->num_rows > 0) {
    while ($credit_details = $credit_details_res->fetch_assoc()) {
        $list_res = $db->query("credit_notes_list", "SELECT SUM(amount) as totals FROM credit_notes_list WHERE credit_note_id = {$credit_details['record_id']}");
        $list = $list_res->fetch_assoc();
        $credit_total += (float) $list['totals'];
    }
}

$net_total = ($subtotal - $credit_total);
// $pdf->Cell(160, 7, 'Subtotal', 0, 0, 'R');
// $pdf->Cell(25, 7, 'R ' . number_format($subtotal, 2), 1, 1, 'L');

// $pdf->Cell(160, 7, 'VAT (15%)', 0, 0, 'R');
// $pdf->Cell(25, 7, 'R ' . number_format($vat, 2), 1, 1, 'L');

// $pdf->Cell(160, 7, 'Net Total', 0, 0, 'R');
// $pdf->Cell(25, 7, 'R ' . number_format($net_total, 2), 1, 1, 'L');

// get payments

$payment_t_res = $db->query("payments", "SELECT SUM(amount) as total FROM payments WHERE invoice_id = '{$payment['invoice_id']}'");
$payment_t = $payment_t_res->fetch_assoc();
$payment_total = $payment_t['total'];


$pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(47, 6, 'Payment Received:', 1, 0);
$pdf->Cell(46, 6, 'R ' . number_format($payment['amount'], 2), 1, 0);
$pdf->Cell(46, 6, 'Balance Outstanding:', 1, 0);
$pdf->Cell(46, 6, 'R ' . number_format($net_total - $payment_total, 2), 1, 1);
$pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(47, 6, 'Amount Due:', 1, 0);
$pdf->Cell(46, 6, 'R ' . number_format($net_total - $payment_total, 2), 1, 0);
$pdf->Cell(46, 6, '', 1, 0);
$pdf->Cell(46, 6, '', 1, 1);
$pdf->Ln(2);
$pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(0, 6, 'BANK DETAILS:', 0, 1);
$pdf->Cell(20, 6, 'NAME:', "LT", 0);
$pdf->Cell(65, 6, $company['name'], "TR", 1);
$pdf->Cell(20, 6, 'BANK:', "L", 0);
$pdf->Cell(65, 6, $company['bank'], "R", 1);
$pdf->Cell(20, 6, 'BRANCH:', "L", 0);
$pdf->Cell(65, 6, $company['branch'], "R", 1);
$pdf->Cell(20, 6, 'TYPE:', "L", 0);
$pdf->Cell(65, 6, $company['account_type'], "R", 1);
$pdf->Cell(20, 6, 'ACC:', "LB", 0);
$pdf->Cell(65, 6, $company['account_no'], "BR", 1);
$pdf->Ln(1);
// Notes & Terms
// $pdf->SetFont('Arial', 'B', 8);
// $pdf->Cell(0, 6, ':', 0, 1);
$pdf->SetFont('Arial', 'B', 10);
$pdf->MultiCell(180, 5, "THANK YOU FOR THE SUPPORT!");
$pdf->MultiCell(180, 5, "PLEASE CONTACT ME SHOULD YOU HAVE ANY QUESTIONS OR QUERIES.");

$pdf->SetFont('Arial', '', 7);

// Output PDF
$pdf->Output('I', 'quotation.pdf');
