<?php
// admin/generate-pdf.php - Versioni me logo proporcionale dhe logjikë 24-orëshe
require_once '../includes/config.php';

if(!isset($_SESSION['admin_logged_in'])) {
    echo json_encode(['success' => false, 'message' => 'Not logged in']);
    exit;
}

header('Content-Type: application/json');

if(!isset($_POST['reservation_id'])) {
    echo json_encode(['success' => false, 'message' => 'Reservation ID required']);
    exit;
}

$id = (int)$_POST['reservation_id'];

if(!file_exists('../includes/tcpdf/tcpdf.php')) {
    echo json_encode(['success' => false, 'message' => 'TCPDF library not installed.']);
    exit;
}

require_once('../includes/tcpdf/tcpdf.php');

$stmt = $pdo->prepare("
    SELECT r.*, c.brand, c.model, c.license_plate, c.year, c.fuel_type, c.transmission, c.seats
    FROM reservations r 
    LEFT JOIN cars c ON r.car_id = c.id 
    WHERE r.id = ?
");
$stmt->execute([$id]);
$reservation = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$reservation) {
    echo json_encode(['success' => false, 'message' => 'Reservation not found']);
    exit;
}

$stmt2 = $pdo->prepare("SELECT * FROM payment_history WHERE reservation_id = ? ORDER BY created_at");
$stmt2->execute([$id]);
$payments = $stmt2->fetchAll(PDO::FETCH_ASSOC);

// Get insurance name if selected
$insurance_name = '';
if($reservation['selected_insurance_id']) {
    $stmt3 = $pdo->prepare("SELECT name, price_per_day, price_one_time, is_daily FROM insurance_types WHERE id = ?");
    $stmt3->execute([$reservation['selected_insurance_id']]);
    $insurance = $stmt3->fetch();
    if($insurance) {
        $insurance_name = $insurance['name'];
    }
}

// Get selected options
$selected_options = [];
if($reservation['selected_options']) {
    $selected_options = json_decode($reservation['selected_options'], true);
    if(!is_array($selected_options)) {
        $selected_options = [];
    }
}

$site_name = getSetting('site_name', $pdo, 'Car Rental Albania');
$site_phone = getSetting('site_phone', $pdo, '');
$site_email = getSetting('site_email', $pdo, '');
$site_address = getSetting('site_address', $pdo, '');
$currency = getSetting('currency', $pdo, '€');

// Get logo URL
$logo_url = getSetting('logo_url', $pdo, '');

// ============================================================
// LLOGARITJA E DITËVE ME LOGJIKËN 24-ORËSHE (1 DITË = 24 ORE)
// ============================================================
$days = getDaysBetween(
    $reservation['pickup_date'],
    $reservation['pickup_time'],
    $reservation['dropoff_date'],
    $reservation['dropoff_time']
);

// Get car total and extras
$car_total = (float)$reservation['total_price'];
$extras_total = (float)($reservation['extras_total'] ?? 0);
$grand_total = (float)($reservation['grand_total'] ?? $car_total);
$paid_amount = (float)$reservation['paid_amount'];
$remaining_balance = $grand_total - $paid_amount;

// Funksioni për të marrë dimensionet e logos proporcionale
function getProportionalLogoSize($logo_path, $max_width = 30, $max_height = 30) {
    if(!file_exists($logo_path)) {
        return ['width' => 30, 'height' => 30];
    }
    
    // Merr dimensionet e imazhit
    $image_info = getimagesize($logo_path);
    if($image_info === false) {
        return ['width' => 30, 'height' => 30];
    }
    
    $orig_width = $image_info[0];
    $orig_height = $image_info[1];
    
    // Llogarit proporcionet
    if($orig_width > $max_width) {
        $ratio = $max_width / $orig_width;
        $new_width = $max_width;
        $new_height = $orig_height * $ratio;
    } else {
        $new_width = $orig_width;
        $new_height = $orig_height;
    }
    
    // Nëse lartësia është akoma shumë e madhe
    if($new_height > $max_height) {
        $ratio = $max_height / $new_height;
        $new_height = $max_height;
        $new_width = $new_width * $ratio;
    }
    
    return [
        'width' => round($new_width, 2),
        'height' => round($new_height, 2)
    ];
}

class MYPDF extends TCPDF {
    public $logo_path = '';
    public $logo_width = 30;
    public $logo_height = 30;
    public $site_name = '';
    public $site_address = '';
    public $site_phone = '';
    public $site_email = '';
    
    public function Header() {
        // Header i vogël dhe i pastër
        if($this->logo_path && file_exists($this->logo_path)) {
            // Logo proporcionale në këndin majtas lart
            $this->Image($this->logo_path, 15, 6, $this->logo_width, $this->logo_height, '', '', '', false, 300, '', false, false, 0, false, false, false);
        }
        
        // Emri i kompanisë dhe informacioni në të djathtë të logos
        $this->SetY(6);
        $this->SetFont('helvetica', 'B', 11);
        $this->Cell(0, 5, $this->site_name, 0, 1, 'R');
        $this->SetFont('helvetica', '', 7);
        $this->Cell(0, 3, $this->site_address, 0, 1, 'R');
        $this->Cell(0, 3, 'Tel: ' . $this->site_phone . ' | Email: ' . $this->site_email, 0, 1, 'R');
        
        // Vijë ndarëse
        $this->Ln(2);
        $this->SetDrawColor(200, 200, 200);
        $this->Line(15, 28, 195, 28);
    }
    
    public function Footer() {
        $this->SetY(-15);
        $this->SetFont('helvetica', 'I', 7);
        $this->Cell(0, 4, 'Thank you for choosing ' . $this->site_name . '!', 0, 1, 'C');
        $this->SetFont('helvetica', 'I', 6);
        $this->Cell(0, 3, 'This invoice is computer generated. No signature required.', 0, 1, 'C');
        $this->Cell(0, 3, 'Page ' . $this->getAliasNumPage() . ' of ' . $this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
    }
}

$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->logo_path = '';
$pdf->site_name = $site_name;
$pdf->site_address = $site_address;
$pdf->site_phone = $site_phone;
$pdf->site_email = $site_email;

// Kontrollo nëse logo ekziston dhe llogarit dimensionet proporcionale
$logo_size = ['width' => 30, 'height' => 30];
if(!empty($logo_url)) {
    $logo_absolute_path = '../' . $logo_url;
    if(file_exists($logo_absolute_path)) {
        $pdf->logo_path = $logo_absolute_path;
        // Llogarit dimensionet proporcionale (max 30px gjerësi, max 25px lartësi)
        $logo_size = getProportionalLogoSize($logo_absolute_path, 30, 25);
        $pdf->logo_width = $logo_size['width'];
        $pdf->logo_height = $logo_size['height'];
    }
}

$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor($site_name);
$pdf->SetTitle('Invoice_' . $reservation['reservation_code']);
$pdf->SetSubject('Rental Invoice');

$pdf->setPrintHeader(true);
$pdf->setPrintFooter(true);
$pdf->SetMargins(15, 38, 15); // Margjina e sipërme për header
$pdf->SetAutoPageBreak(true, 30);
$pdf->AddPage();

$pdf->SetFont('helvetica', '', 9);

// ============================================================
// INVOICE NUMBER AND DATE
// ============================================================
$pdf->SetFont('helvetica', 'B', 11);
$pdf->Cell(0, 6, 'INVOICE', 0, 1, 'C');
$pdf->Ln(3);

$pdf->SetFont('helvetica', '', 9);
$pdf->Cell(100, 5, 'Invoice Number: ' . $reservation['reservation_code'], 0, 0);
$pdf->Cell(0, 5, 'Invoice Date: ' . date('d/m/Y'), 0, 1, 'R');
$pdf->Ln(3);

// ============================================================
// BILL TO AND VEHICLE (2 kolona)
// ============================================================
$pdf->SetFont('helvetica', 'B', 9);
$pdf->Cell(90, 5, 'BILL TO', 0, 0);
$pdf->Cell(0, 5, 'VEHICLE', 0, 1);
$pdf->SetFont('helvetica', '', 8);
$pdf->MultiCell(90, 4, htmlspecialchars($reservation['customer_name']) . "\n" . htmlspecialchars($reservation['customer_email']) . "\n" . htmlspecialchars($reservation['customer_phone']), 0, 'L', 0, 0);
$pdf->MultiCell(0, 4, htmlspecialchars($reservation['brand'] . ' ' . $reservation['model']) . "\nPlate: " . htmlspecialchars($reservation['license_plate']) . "\n" . $reservation['year'] . ' | ' . $reservation['transmission'] . ' | ' . $reservation['fuel_type'] . ' | ' . $reservation['seats'] . ' seats', 0, 'L', 0, 1);
$pdf->Ln(3);

// ============================================================
// PICKUP AND RETURN
// ============================================================
$pdf->SetFont('helvetica', 'B', 9);
$pdf->Cell(90, 5, 'PICKUP', 0, 0);
$pdf->Cell(0, 5, 'RETURN', 0, 1);
$pdf->SetFont('helvetica', '', 8);
$pdf->Cell(90, 4, date('d/m/Y', strtotime($reservation['pickup_date'])) . ' at ' . substr($reservation['pickup_time'], 0, 5), 0, 0);
$pdf->Cell(0, 4, date('d/m/Y', strtotime($reservation['dropoff_date'])) . ' at ' . substr($reservation['dropoff_time'], 0, 5), 0, 1);
$pdf->Cell(90, 4, htmlspecialchars($reservation['pickup_location']), 0, 0);
$pdf->Cell(0, 4, htmlspecialchars($reservation['dropoff_location']), 0, 1);
$pdf->Ln(2);
$pdf->SetFont('helvetica', 'B', 9);
$pdf->Cell(0, 4, 'Total Days: ' . $days . ' day' . ($days > 1 ? 's' : ''), 0, 1);
$pdf->Ln(5);

// ============================================================
// RENTAL CHARGES TABLE
// ============================================================
$pdf->SetFont('helvetica', 'B', 9);
$pdf->Cell(0, 6, 'RENTAL CHARGES', 0, 1);

// Table header
$pdf->SetFillColor(245, 245, 245);
$pdf->SetFont('helvetica', 'B', 8);
$pdf->Cell(100, 6, 'Description', 1, 0, 'L', 1);
$pdf->Cell(25, 6, 'Qty', 1, 0, 'C', 1);
$pdf->Cell(30, 6, 'Rate', 1, 0, 'R', 1);
$pdf->Cell(35, 6, 'Amount', 1, 1, 'R', 1);

// Car rental row
$daily_rate = $days > 0 ? $car_total / $days : 0;
$pdf->SetFont('helvetica', '', 8);
$pdf->Cell(100, 6, htmlspecialchars($reservation['brand'] . ' ' . $reservation['model']) . ' - Daily Rental', 1, 0, 'L');
$pdf->Cell(25, 6, $days . ' day' . ($days > 1 ? 's' : ''), 1, 0, 'C');
$pdf->Cell(30, 6, $currency . number_format($daily_rate, 2), 1, 0, 'R');
$pdf->Cell(35, 6, $currency . number_format($car_total, 2), 1, 1, 'R');

// Insurance row
if($insurance_name && $reservation['selected_insurance_price'] > 0) {
    $insurance_price = (float)$reservation['selected_insurance_price'];
    $pdf->SetFont('helvetica', '', 8);
    $pdf->Cell(100, 6, 'Insurance: ' . htmlspecialchars($insurance_name), 1, 0, 'L');
    $pdf->Cell(25, 6, '1', 1, 0, 'C');
    $pdf->Cell(30, 6, $currency . number_format($insurance_price, 2), 1, 0, 'R');
    $pdf->Cell(35, 6, $currency . number_format($insurance_price, 2), 1, 1, 'R');
}

// Additional Options rows
foreach($selected_options as $opt) {
    $opt_name = htmlspecialchars($opt['name']);
    $opt_quantity = isset($opt['quantity']) ? (int)$opt['quantity'] : 1;
    $opt_price = (float)($opt['price'] ?? 0);
    $rate_per_item = $opt_quantity > 0 ? $opt_price / $opt_quantity : 0;
    $qty_text = $opt_quantity . ' x';
    
    $pdf->SetFont('helvetica', '', 8);
    $pdf->Cell(100, 6, $opt_name, 1, 0, 'L');
    $pdf->Cell(25, 6, $qty_text, 1, 0, 'C');
    $pdf->Cell(30, 6, $currency . number_format($rate_per_item, 2), 1, 0, 'R');
    $pdf->Cell(35, 6, $currency . number_format($opt_price, 2), 1, 1, 'R');
}

// Subtotal row (only if extras exist)
if($extras_total > 0) {
    $pdf->SetFont('helvetica', 'B', 8);
    $pdf->SetFillColor(250, 250, 250);
    $pdf->Cell(155, 6, 'Subtotal (Car + Extras):', 1, 0, 'R', 1);
    $pdf->Cell(35, 6, $currency . number_format($grand_total, 2), 1, 1, 'R', 1);
}

$pdf->Ln(3);

// ============================================================
// TOTAL SECTION
// ============================================================
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(130, 5, 'Grand Total:', 0, 0, 'R');
$pdf->Cell(0, 5, $currency . number_format($grand_total, 2), 0, 1, 'R');

if($extras_total > 0) {
    $pdf->SetFont('helvetica', '', 7);
    $pdf->Cell(130, 3, '(Car: ' . $currency . number_format($car_total, 2) . ' + Extras: ' . $currency . number_format($extras_total, 2) . ')', 0, 0, 'R');
    $pdf->Cell(0, 3, '', 0, 1, 'R');
}

$pdf->Ln(4);

// ============================================================
// PAYMENT SUMMARY
// ============================================================
$pdf->SetFont('helvetica', 'B', 9);
$pdf->Cell(0, 6, 'PAYMENT SUMMARY', 0, 1);
$pdf->SetFont('helvetica', '', 8);
$pdf->Cell(100, 5, 'Total Amount:', 0, 0);
$pdf->Cell(0, 5, $currency . number_format($grand_total, 2), 0, 1);
$pdf->Cell(100, 5, 'Amount Paid:', 0, 0);
$pdf->Cell(0, 5, $currency . number_format($paid_amount, 2), 0, 1);

if($remaining_balance > 0) {
    $pdf->SetFont('helvetica', 'B', 8);
    $pdf->SetTextColor(220, 53, 69);
    $pdf->Cell(100, 5, 'Balance Due:', 0, 0);
    $pdf->Cell(0, 5, $currency . number_format($remaining_balance, 2), 0, 1);
    $pdf->SetTextColor(0, 0, 0);
} elseif($remaining_balance < 0) {
    $pdf->SetFont('helvetica', 'B', 8);
    $pdf->SetTextColor(40, 167, 69);
    $pdf->Cell(100, 5, 'Refund Due:', 0, 0);
    $pdf->Cell(0, 5, $currency . number_format(abs($remaining_balance), 2), 0, 1);
    $pdf->SetTextColor(0, 0, 0);
} else {
    $pdf->SetFont('helvetica', 'B', 8);
    $pdf->SetTextColor(40, 167, 69);
    $pdf->Cell(100, 5, 'Status:', 0, 0);
    $pdf->Cell(0, 5, 'PAID IN FULL', 0, 1);
    $pdf->SetTextColor(0, 0, 0);
}

$pdf->Ln(5);

// ============================================================
// PAYMENT HISTORY TABLE
// ============================================================
$pdf->SetFont('helvetica', 'B', 9);
$pdf->Cell(0, 6, 'PAYMENT HISTORY', 0, 1);

$pdf->SetFillColor(245, 245, 245);
$pdf->SetFont('helvetica', 'B', 8);
$pdf->Cell(45, 6, 'Date', 1, 0, 'L', 1);
$pdf->Cell(35, 6, 'Method', 1, 0, 'L', 1);
$pdf->Cell(40, 6, 'Amount', 1, 0, 'R', 1);
$pdf->Cell(0, 6, 'Notes', 1, 1, 'L', 1);

$pdf->SetFont('helvetica', '', 8);
if(count($payments) > 0) {
    foreach($payments as $payment) {
        $amount = (float)$payment['amount'];
        $amount_prefix = $amount < 0 ? '(Refund) ' : '';
        $pdf->Cell(45, 5, date('d/m/Y', strtotime($payment['created_at'])), 1, 0, 'L');
        $pdf->Cell(35, 5, ucfirst(htmlspecialchars($payment['payment_method'])), 1, 0, 'L');
        $pdf->Cell(40, 5, $amount_prefix . $currency . number_format(abs($amount), 2), 1, 0, 'R');
        $pdf->Cell(0, 5, htmlspecialchars(substr($payment['notes'] ?? '', 0, 35)), 1, 1, 'L');
    }
} else {
    $pdf->Cell(0, 6, 'No payments recorded', 1, 1, 'C');
}

$pdf->Ln(5);

// ============================================================
// NOTES (nese ka)
// ============================================================
if($reservation['notes']) {
    $pdf->SetFont('helvetica', 'B', 9);
    $pdf->Cell(0, 5, 'NOTES', 0, 1);
    $pdf->SetFont('helvetica', '', 8);
    $pdf->MultiCell(0, 4, htmlspecialchars($reservation['notes']), 0, 'L');
}

$pdf_content = $pdf->Output('invoice_' . $reservation['reservation_code'] . '.pdf', 'S');
$pdf_base64 = base64_encode($pdf_content);

echo json_encode(['success' => true, 'pdf' => $pdf_base64, 'filename' => 'Invoice_' . $reservation['reservation_code'] . '.pdf']);
?>