<?php
// petty_cash_in_multi_voucher_print.php
include_once('../fpdf/fpdfreportlogo.php');
include_once('../classes/manager.class.php');
include_once('../includes/number_to_words.php');
$m = new Manager();

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

// Filters
$datefrom = $_GET['datefrom'] ?? date('d-m-Y', strtotime('-30 days'));
$dateto   = $_GET['dateto']   ?? date('d-m-Y');

$qryDate = date("Y-m-d", strtotime($datefrom));
$qryTo   = date("Y-m-d", strtotime($dateto));

// Build filter
$filter = " WHERE DATE_FORMAT(`date`, '%Y-%m-%d') >= '$qryDate' 
            AND DATE_FORMAT(`date`, '%Y-%m-%d') <= '$qryTo' 
            ORDER BY `date` ASC, `id` ASC";

// Fetch vouchers
$vouchers = PettyCashIn::GetPettyCashInList($filter);
if (!$vouchers || count($vouchers) == 0) {
    die("No petty cash vouchers found for the selected filters.");
}

class PDF extends FPDF {
    function Header() {
        $this->Image(PROJECT_URL . 'images/logo_left_print.png', 10, 6, 20);
        $this->Image(PROJECT_URL . 'images/logo_right_print.png', 170, 6, 20);
        $this->SetFont('Arial', 'B', 16);
        $this->Cell(0, 8, 'Cash In Voucher', 0, 1, 'C');
        $this->Ln();
    }
}

$pdf = new PDF('P','mm','A4');

foreach ($vouchers as $pc) {
    // Meta & safe fallbacks
    $voucherNo   = !empty($pc->voucher_no) ? $pc->voucher_no : ('PCI-' . str_pad($pc->id, 6, '0', STR_PAD_LEFT));
    $pcDate      = !empty($pc->date) ? $pc->date : (!empty($pc->create_date) ? $pc->create_date : $pc->datetime);
    $voucherDate = $pcDate ? date('d-M-Y', strtotime($pcDate)) : date('d-M-Y');
    $amount      = (float)$pc->amount;
    $desc        = isset($pc->description) ? $pc->description : '';

    // NEW: Source type (bank / other)
    $sourceType = isset($pc->source_type) && $pc->source_type ? $pc->source_type : 'bank';

    // Bank name (same pattern as expense voucher)
    $bankName = '';
    if (!empty($pc->bank_id)) {
        $bank = BankSetup::GetBankSetupById($pc->bank_id);
        if ($bank) {
            $bankName = $bank->bank_name;
        }
    }

    // Cheque no field name in petty cash in
    $chequeNo = isset($pc->chq_no) ? $pc->chq_no : '';

    // Issued by (petty cash uses created_by)
    $issuedBy = '-';
    if (!empty($pc->created_by)) {
        $usr = User_setup::GetUserSetupId($pc->created_by);
        $issuedBy = ($usr && isset($usr->username)) ? $usr->username : '-';
    }
    $approvedBy = '-';
    $receivedBy = 'Petty Cash';

    $amountWords = 'Rupees ' . ucwords(NumberToWords::convert($amount)) . ' only';

    // ====== Decide Debit / Credit Titles based on source_type ======
    if ($sourceType === 'bank') {
        // Bank → Petty Cash
        $debitTitle       = 'Petty Cash (Received from ' . ($bankName ?: 'Bank') . ')';
        $debitCashCheque  = ($chequeNo ? $chequeNo : 'Cheque');

        $creditTitle      = ($bankName ?: 'Bank');
        $creditCashCheque = ($chequeNo ? $chequeNo : 'Cheque');
    } else {
        // Other source (wastage sold, other income, etc.)
        $debitTitle       = 'Petty Cash (Received from Other)';
        $debitCashCheque  = 'Cash';

        // Use description as title for credit side if available
        $creditTitle      = !empty($desc) ? $desc : 'Other Source';
        $creditCashCheque = 'Cash';
    }
    // ===============================================================

    // Page per voucher
    $pdf->AddPage();
    $pdf->SetFont('Arial','',11);

    // Voucher header row
    $pdf->SetFont('Arial', 'B', 11);
    $pdf->Cell(94,6,"Voucher No: ".$voucherNo,1,0,'L');
    $pdf->Cell(94,6,"Date: ".$voucherDate,1,1,'R');
    $pdf->Ln(2);

    // Debit
    $pdf->SetFont('Arial','B',12);
    $pdf->Cell(188,6,'Debit',1,1,'C');
    $pdf->SetFont('Arial','B',11);
    $pdf->Cell(114,6,'Title',1,0,'C');
    $pdf->Cell(40,6,'Cash / Cheque',1,0,'C');
    $pdf->Cell(34,6,'Amount',1,1,'C');

    $pdf->SetFont('Arial','',11);
    $pdf->Cell(114,6,$debitTitle,1,0);
    $pdf->Cell(40,6,$debitCashCheque,1,0);
    $pdf->Cell(34,6,number_format($amount,0),1,1,'R');

    $pdf->SetFont('Arial','B',11);
    $pdf->Cell(154,6,'Total',1,0,'R');
    $pdf->Cell(34,6,number_format($amount,0),1,1,'R');

    // Credit
    $pdf->Ln(2);
    $pdf->SetFont('Arial','B',12);
    $pdf->Cell(188,6,'Credit',1,1,'C');
    $pdf->SetFont('Arial','B',11);
    $pdf->Cell(114,6,'Title',1,0,'C');
    $pdf->Cell(40,6,'Cash / Cheque',1,0,'C');
    $pdf->Cell(34,6,'Amount',1,1,'C');

    $pdf->SetFont('Arial','',11);
    $pdf->Cell(114,6,$creditTitle,1,0);
    $pdf->Cell(40,6,$creditCashCheque,1,0);
    $pdf->Cell(34,6,number_format($amount,0),1,1,'R');

    $pdf->SetFont('Arial','B',11);
    $pdf->Cell(154,6,'Total',1,0,'R');
    $pdf->Cell(34,6,number_format($amount,0),1,1,'R');

    // Amount in words
    $pdf->Ln(2);
    $pdf->SetFont('Arial','B',11);
    $pdf->Cell(188,6,'Amount in Words',1,1,'C');
    $pdf->SetFont('Arial','',11);
    $pdf->MultiCell(188,6,$amountWords,1);

    // Remarks
    $pdf->Ln(2);
    $pdf->SetFont('Arial','B',11);
    $pdf->Cell(188,6,'Remarks',1,1,'C');
    $pdf->SetFont('Arial','',11);
    $pdf->MultiCell(188,6,$desc,1);

    // Signatures
    $pdf->Ln(2);
    $pdf->SetFont('Arial','B',11);
    $pdf->Cell(50,6,'Issued by:',1,0,'C');
    $pdf->Cell(50,6,'Approved by:',1,0,'C');
    $pdf->Cell(88,6,'Received by:',1,1,'C');

    $pdf->SetFont('Arial','',11);
    $pdf->Cell(50,20,"",1,0,'C');
    $pdf->Cell(50,20,"",1,0,'C');
    $pdf->Cell(88,20,"",1,1,'C');

    $pdf->Cell(50,6,$issuedBy,1,0,'C');
    $pdf->Cell(50,6,'Asif Hussain',1,0,'C');
    $pdf->Cell(88,6,'Asad',1,1,'C');

    $pdf->Ln(4);
}

$pdf->Output();
