<?php
session_start();
include 'layouts/dbconn.php';
require('fpdf/fpdf.php');

// Check if the user is not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if invoice ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: file_list.php');
    exit();
}

$invoice_id = intval($_GET['id']);

// Get invoice details
$query = "SELECT i.*, c.first_name as customer_name, c.email as customer_email, c.address as customer_address,
          c.phone_number as customer_phone, f.currency as file_currency, f.id as file_id
          FROM invoices i 
          LEFT JOIN customers c ON i.customer_id = c.customer_id
          LEFT JOIN files f ON i.file_number = f.file_number
          WHERE i.invoice_id = ?";

$stmt = $conn->prepare($query);
$stmt->bind_param('i', $invoice_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die("Invoice not found");
}

$invoice = $result->fetch_assoc();
$file_number = $invoice['file_number'];
$currency = $invoice['file_currency'] ?? '$';

// Extract invoice items from the database (in this implementation, we'll use the name, description, quantity, price fields)
// In a production system, you'd likely have a separate invoice_items table
$invoice_items = [];
$item_name = $invoice['name'] ?? ''; 
$item_description = $invoice['description'] ?? '';
$item_quantity = $invoice['quantity'] ?? 0;
$item_price = $invoice['price'] ?? 0;

if (!empty($item_name)) {
    $invoice_items[] = [
        'name' => $item_name,
        'description' => $item_description,
        'quantity' => $item_quantity,
        'price' => $item_price,
        'total' => $item_quantity * $item_price
    ];
}

// Get company settings
$settings_query = "SELECT * FROM settings WHERE setting_key IN ('system_name', 'address', 'tel_1', 'tel_2')";
$settings_result = $conn->query($settings_query);
$settings = [];

if ($settings_result->num_rows > 0) {
    while ($row = $settings_result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
}

// Function to convert number to words (for total amount)
function numberToWords($number) {
    $hyphen = '-';
    $conjunction = ' and ';
    $separator = ', ';
    $negative = 'negative ';
    $decimal = ' point ';
    $dictionary = array(
        0 => 'zero',
        1 => 'one',
        2 => 'two',
        3 => 'three',
        4 => 'four',
        5 => 'five',
        6 => 'six',
        7 => 'seven',
        8 => 'eight',
        9 => 'nine',
        10 => 'ten',
        11 => 'eleven',
        12 => 'twelve',
        13 => 'thirteen',
        14 => 'fourteen',
        15 => 'fifteen',
        16 => 'sixteen',
        17 => 'seventeen',
        18 => 'eighteen',
        19 => 'nineteen',
        20 => 'twenty',
        30 => 'thirty',
        40 => 'forty',
        50 => 'fifty',
        60 => 'sixty',
        70 => 'seventy',
        80 => 'eighty',
        90 => 'ninety',
        100 => 'hundred',
        1000 => 'thousand',
        1000000 => 'million',
        1000000000 => 'billion',
        1000000000000 => 'trillion',
        1000000000000000 => 'quadrillion',
        1000000000000000000 => 'quintillion'
    );
    
    if (!is_numeric($number)) {
        return false;
    }
    
    if (($number >= 0 && (int)$number < 0) || (int)$number < 0 - PHP_INT_MAX) {
        // overflow
        return false;
    }
    
    if ($number < 0) {
        return $negative . numberToWords(abs($number));
    }
    
    $string = $fraction = null;
    
    if (strpos($number, '.') !== false) {
        list($number, $fraction) = explode('.', $number);
    }
    
    switch (true) {
        case $number < 21:
            $string = $dictionary[$number];
            break;
        case $number < 100:
            $tens = ((int)($number / 10)) * 10;
            $units = $number % 10;
            $string = $dictionary[$tens];
            if ($units) {
                $string .= $hyphen . $dictionary[$units];
            }
            break;
        case $number < 1000:
            $hundreds = $number / 100;
            $remainder = $number % 100;
            $string = $dictionary[(int)$hundreds] . ' ' . $dictionary[100];
            if ($remainder) {
                $string .= $conjunction . numberToWords($remainder);
            }
            break;
        default:
            $baseUnit = pow(1000, floor(log($number, 1000)));
            $numBaseUnits = (int)($number / $baseUnit);
            $remainder = $number % $baseUnit;
            $string = numberToWords($numBaseUnits) . ' ' . $dictionary[$baseUnit];
            if ($remainder) {
                $string .= $remainder < 100 ? $conjunction : $separator;
                $string .= numberToWords($remainder);
            }
            break;
    }
    
    if (null !== $fraction && is_numeric($fraction)) {
        $string .= $decimal;
        $words = array();
        foreach (str_split((string)$fraction) as $number) {
            $words[] = $dictionary[$number];
        }
        $string .= implode(' ', $words);
    }
    
    return $string;
}

// Extend FPDF class to create custom header and footer
class InvoicePDF extends FPDF {
    private $company_name;
    private $company_address;
    private $company_tel;
    private $invoice_number;
    private $invoice_date;
    private $invoice_due_date;
    private $invoice_status;
    
    function setInvoiceInfo($company_name, $company_address, $company_tel, $invoice_number, $invoice_date, $invoice_due_date, $invoice_status) {
        $this->company_name = $company_name;
        $this->company_address = $company_address;
        $this->company_tel = $company_tel;
        $this->invoice_number = $invoice_number;
        $this->invoice_date = $invoice_date;
        $this->invoice_due_date = $invoice_due_date;
        $this->invoice_status = $invoice_status;
    }
    
    function Header() {
        // Company logo (if available)
        // $this->Image('logo.png', 10, 10, 30);
        
        // Company information (left side)
        $this->SetFont('Arial', 'B', 14);
        $this->Cell(0, 10, $this->company_name, 0, 1);
        $this->SetFont('Arial', '', 10);
        $this->MultiCell(0, 5, $this->company_address, 0, 'L');
        $this->Cell(0, 5, 'Tel: ' . $this->company_tel, 0, 1);
        
        $this->Ln(10);
        
        // Invoice title and details (right side)
        $this->SetFont('Arial', 'B', 18);
        $this->Cell(0, 10, 'INVOICE', 0, 1, 'R');
        $this->SetFont('Arial', '', 10);
        $this->Cell(0, 6, 'Invoice #: ' . $this->invoice_number, 0, 1, 'R');
        $this->Cell(0, 6, 'Date: ' . $this->invoice_date, 0, 1, 'R');
        $this->Cell(0, 6, 'Due Date: ' . $this->invoice_due_date, 0, 1, 'R');
        $this->Cell(0, 6, 'Status: ' . strtoupper($this->invoice_status), 0, 1, 'R');
        
        $this->Ln(10);
    }
    
    function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 8);
        $this->Cell(0, 10, 'Thank you for your business! This is a computer generated invoice and does not require a signature.', 0, 0, 'C');
        $this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'R');
    }
}

// Function to format dates
function formatDate($date) {
    if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
        return 'N/A';
    }
    return date('d M Y', strtotime($date));
}

// Create PDF instance
$pdf = new InvoicePDF();
$pdf->AliasNbPages();
$pdf->AddPage();

// Set invoice information
$pdf->setInvoiceInfo(
    $settings['system_name'] ?? 'Royal Freight System',
    $settings['address'] ?? 'P.O.Box-85636-80100, Mombasa',
    $settings['tel_1'] ?? '',
    $invoice['invoice_number'],
    formatDate($invoice['issue_date']),
    formatDate($invoice['due_date']),
    ucfirst($invoice['status'])
);

// Billing and Shipping details
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(95, 6, 'FROM:', 0, 0);
$pdf->Cell(95, 6, 'BILL TO:', 0, 1);

$pdf->SetFont('Arial', '', 10);
// From address
$pdf->MultiCell(95, 5, $settings['system_name'] ?? 'Royal Freight System' . "\n" . 
                     ($settings['address'] ?? 'P.O.Box-85636-80100, Mombasa') . "\n" . 
                     'Tel: ' . ($settings['tel_1'] ?? ''), 0, 'L');

// Reset Y position to align with "FROM" block
$pdf->SetXY(105, $pdf->GetY() - 15);

// To address
$customer_details = $invoice['customer_name'] . "\n";
if (!empty($invoice['customer_address'])) {
    $customer_details .= $invoice['customer_address'] . "\n";
}
if (!empty($invoice['customer_phone'])) {
    $customer_details .= 'Tel: ' . $invoice['customer_phone'] . "\n";
}
if (!empty($invoice['customer_email'])) {
    $customer_details .= 'Email: ' . $invoice['customer_email'];
}
$pdf->MultiCell(95, 5, $customer_details, 0, 'L');

$pdf->Ln(10);

// Reference information
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(40, 8, 'File Reference:', 1);
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(150, 8, $invoice['file_number'], 1, 1);

$pdf->Ln(10);

// Invoice items table header
$pdf->SetFillColor(240, 240, 240);
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(10, 8, '#', 1, 0, 'C', true);
$pdf->Cell(50, 8, 'Item', 1, 0, 'L', true);
$pdf->Cell(65, 8, 'Description', 1, 0, 'L', true);
$pdf->Cell(15, 8, 'Qty', 1, 0, 'C', true);
$pdf->Cell(25, 8, 'Unit Price', 1, 0, 'R', true);
$pdf->Cell(25, 8, 'Total', 1, 1, 'R', true);

// Invoice items
$pdf->SetFont('Arial', '', 10);
if (!empty($invoice_items)) {
    foreach ($invoice_items as $index => $item) {
        $pdf->Cell(10, 8, $index + 1, 1, 0, 'C');
        $pdf->Cell(50, 8, $item['name'], 1, 0, 'L');
        $pdf->Cell(65, 8, $item['description'], 1, 0, 'L');
        $pdf->Cell(15, 8, $item['quantity'], 1, 0, 'C');
        $pdf->Cell(25, 8, $currency . ' ' . number_format($item['price'], 2), 1, 0, 'R');
        $pdf->Cell(25, 8, $currency . ' ' . number_format($item['total'], 2), 1, 1, 'R');
    }
} else {
    $pdf->Cell(10, 8, '1', 1, 0, 'C');
    $pdf->Cell(50, 8, 'Shipping Services', 1, 0, 'L');
    $pdf->Cell(65, 8, 'Services for shipment ' . $file_number, 1, 0, 'L');
    $pdf->Cell(15, 8, '1', 1, 0, 'C');
    $pdf->Cell(25, 8, $currency . ' ' . number_format($invoice['total_amount'], 2), 1, 0, 'R');
    $pdf->Cell(25, 8, $currency . ' ' . number_format($invoice['total_amount'], 2), 1, 1, 'R');
}

// Totals section
$pdf->Ln(5);
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(140, 8, '', 0, 0);
$pdf->Cell(25, 8, 'Subtotal:', 1, 0, 'L');
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(25, 8, $currency . ' ' . number_format($invoice['total_amount'], 2), 1, 1, 'R');

$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(140, 8, '', 0, 0);
$pdf->Cell(25, 8, 'Total:', 1, 0, 'L', true);
$pdf->Cell(25, 8, $currency . ' ' . number_format($invoice['total_amount'], 2), 1, 1, 'R', true);

// Amount in words
$pdf->Ln(5);
$pdf->SetFont('Arial', 'I', 10);
$pdf->Cell(0, 8, 'Amount in words: ' . ucfirst(numberToWords($invoice['total_amount'])) . ' ' . ($currency == '$' ? 'Dollars' : $currency) . ' Only', 0, 1);

// Notes
if (!empty($invoice['notes'])) {
    $pdf->Ln(10);
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->Cell(0, 8, 'Notes / Terms', 0, 1);
    $pdf->SetFont('Arial', '', 10);
    $pdf->MultiCell(0, 6, $invoice['notes'], 0, 'L');
}

// Output PDF
$pdf->Output('Invoice_' . $invoice['invoice_number'] . '.pdf', 'I');
?>