<?php
session_start();
require_once 'layouts/dbconn.php';
require_once 'layouts/session.php';
require_once 'fpdf/fpdf.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get dispensing ID
$dispensing_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$dispensing_id) {
    die('Invalid dispensing ID');
}

// Fetch dispensing details
$sql = "SELECT d.*, 
               ip.provider_name,
               u.full_name as dispensed_by_name
        FROM pharmacy_dispensing d
        LEFT JOIN insurance_providers ip ON d.insurance_provider_id = ip.provider_id
        LEFT JOIN users u ON d.dispensed_by = u.user_id
        WHERE d.dispensing_id = ?";

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

if ($result->num_rows === 0) {
    die('Dispensing record not found');
}

$dispensing = $result->fetch_assoc();

// Fetch dispensing items
$items_sql = "SELECT di.*, pi.item_code, pi.dosage_form, pi.strength
              FROM pharmacy_dispensing_items di
              LEFT JOIN pharmacy_inventory pi ON di.inventory_id = pi.inventory_id
              WHERE di.dispensing_id = ?";

$stmt = $conn->prepare($items_sql);
$stmt->bind_param('i', $dispensing_id);
$stmt->execute();
$items_result = $stmt->get_result();
$items = $items_result->fetch_all(MYSQLI_ASSOC);

// Get hospital settings
$settings_sql = "SELECT setting_key, setting_value FROM system_settings 
                 WHERE setting_key IN ('hospital_name', 'hospital_address', 'hospital_phone', 
                                      'hospital_email', 'hospital_logo')";
$settings_result = $conn->query($settings_sql);
$settings = [];
while ($row = $settings_result->fetch_assoc()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

// Create PDF
class PDF extends FPDF {
    private $hospital_name;
    private $hospital_address;
    private $hospital_phone;
    private $hospital_email;
    
    function __construct($settings) {
        parent::__construct();
        $this->hospital_name = $settings['hospital_name'] ?? 'ENT Hospital';
        $this->hospital_address = $settings['hospital_address'] ?? '';
        $this->hospital_phone = $settings['hospital_phone'] ?? '';
        $this->hospital_email = $settings['hospital_email'] ?? '';
    }
    
    function Header() {
        // Hospital logo
        $logo_path = 'assets/images/logo.png';
        if (file_exists($logo_path)) {
            $this->Image($logo_path, 10, 6, 30);
        }
        
        // Hospital details
        $this->SetFont('Arial', 'B', 16);
        $this->SetX(45);
        $this->Cell(0, 8, $this->hospital_name, 0, 1, 'L');
        
        $this->SetFont('Arial', '', 10);
        $this->SetX(45);
        $this->Cell(0, 5, $this->hospital_address, 0, 1, 'L');
        
        $this->SetX(45);
        $this->Cell(0, 5, 'Tel: ' . $this->hospital_phone . ' | Email: ' . $this->hospital_email, 0, 1, 'L');
        
        $this->Ln(5);
        
        // Document title
        $this->SetFont('Arial', 'B', 14);
        $this->SetFillColor(59, 130, 246);
        $this->SetTextColor(255, 255, 255);
        $this->Cell(0, 10, 'PHARMACY DISPENSING INVOICE', 0, 1, 'C', true);
        $this->SetTextColor(0, 0, 0);
        $this->Ln(5);
    }
    
    function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 8);
        $this->SetTextColor(128, 128, 128);
        $this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');
    }
}

$pdf = new PDF($settings);
$pdf->AliasNbPages();
$pdf->AddPage();

// Dispensing Information
$pdf->SetFont('Arial', 'B', 11);
$pdf->SetFillColor(240, 240, 240);
$pdf->Cell(95, 7, 'Dispensing Details', 1, 0, 'L', true);
$pdf->Cell(95, 7, 'Patient Information', 1, 1, 'L', true);

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

// Left column - Dispensing details
$pdf->Cell(45, 6, 'Dispensing No:', 1, 0);
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(50, 6, $dispensing['dispensing_number'], 1, 0);
$pdf->SetFont('Arial', '', 10);

// Right column - Patient details
$pdf->Cell(40, 6, 'Patient Name:', 1, 0);
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(55, 6, $dispensing['patient_name'], 1, 1);
$pdf->SetFont('Arial', '', 10);

$pdf->Cell(45, 6, 'Date:', 1, 0);
$pdf->Cell(50, 6, date('d/m/Y H:i', strtotime($dispensing['dispensing_date'])), 1, 0);
$pdf->Cell(40, 6, 'Patient Type:', 1, 0);
$pdf->Cell(55, 6, $dispensing['patient_type'], 1, 1);

$pdf->Cell(45, 6, 'Dispensed By:', 1, 0);
$pdf->Cell(50, 6, $dispensing['dispensed_by_name'], 1, 0);
$pdf->Cell(40, 6, 'Phone:', 1, 0);
$pdf->Cell(55, 6, $dispensing['patient_phone'] ?? 'N/A', 1, 1);

$pdf->Cell(45, 6, 'Payment Method:', 1, 0);
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(50, 6, $dispensing['payment_method'], 1, 0);
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(40, 6, 'Payment Status:', 1, 0);

// Color code payment status
if ($dispensing['payment_status'] === 'PAID') {
    $pdf->SetTextColor(0, 150, 0);
} elseif ($dispensing['payment_status'] === 'PENDING') {
    $pdf->SetTextColor(255, 140, 0);
} else {
    $pdf->SetTextColor(200, 0, 0);
}
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(55, 6, $dispensing['payment_status'], 1, 1);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetFont('Arial', '', 10);

// Insurance details if applicable
if ($dispensing['payment_method'] === 'INSURANCE' && !empty($dispensing['provider_name'])) {
    $pdf->Cell(45, 6, 'Insurance Provider:', 1, 0);
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->Cell(145, 6, $dispensing['provider_name'], 1, 1);
    $pdf->SetFont('Arial', '', 10);
    
    if (!empty($dispensing['insurance_claim_number'])) {
        $pdf->Cell(45, 6, 'Claim Number:', 1, 0);
        $pdf->Cell(145, 6, $dispensing['insurance_claim_number'], 1, 1);
    }
}

$pdf->Ln(5);

// Items table
$pdf->SetFont('Arial', 'B', 10);
$pdf->SetFillColor(59, 130, 246);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(10, 8, '#', 1, 0, 'C', true);
$pdf->Cell(80, 8, 'Medication', 1, 0, 'L', true);
$pdf->Cell(25, 8, 'Quantity', 1, 0, 'C', true);
$pdf->Cell(30, 8, 'Unit Price', 1, 0, 'R', true);
$pdf->Cell(45, 8, 'Total', 1, 1, 'R', true);
$pdf->SetTextColor(0, 0, 0);

$pdf->SetFont('Arial', '', 9);
$counter = 1;

foreach ($items as $item) {
    $height = 6;
    $medication_name = $item['item_name'];
    if (!empty($item['strength'])) {
        $medication_name .= ' (' . $item['strength'] . ')';
    }
    
    $pdf->Cell(10, $height, $counter++, 1, 0, 'C');
    $pdf->Cell(80, $height, $medication_name, 1, 0, 'L');
    $pdf->Cell(25, $height, $item['quantity'], 1, 0, 'C');
    $pdf->Cell(30, $height, 'KES ' . number_format($item['unit_price'], 2), 1, 0, 'R');
    $pdf->Cell(45, $height, 'KES ' . number_format($item['total_price'], 2), 1, 1, 'R');
    
    // Add dosage instructions if available
    if (!empty($item['dosage_instructions'])) {
        $pdf->SetFont('Arial', 'I', 8);
        $pdf->SetTextColor(100, 100, 100);
        $pdf->Cell(10, 5, '', 0, 0);
        $pdf->MultiCell(180, 4, 'Dosage: ' . $item['dosage_instructions'], 0, 'L');
        $pdf->SetTextColor(0, 0, 0);
        $pdf->SetFont('Arial', '', 9);
    }
}

// Totals
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(145, 7, 'TOTAL AMOUNT', 1, 0, 'R');
$pdf->SetFont('Arial', 'B', 12);
$pdf->SetTextColor(59, 130, 246);
$pdf->Cell(45, 7, 'KES ' . number_format($dispensing['total_amount'], 2), 1, 1, 'R');
$pdf->SetTextColor(0, 0, 0);

$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(145, 7, 'AMOUNT PAID', 1, 0, 'R');
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(45, 7, 'KES ' . number_format($dispensing['amount_paid'], 2), 1, 1, 'R');

$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(145, 7, 'BALANCE', 1, 0, 'R');
$pdf->SetFont('Arial', 'B', 11);
$balance = $dispensing['balance'];
if ($balance > 0) {
    $pdf->SetTextColor(200, 0, 0);
}
$pdf->Cell(45, 7, 'KES ' . number_format($balance, 2), 1, 1, 'R');
$pdf->SetTextColor(0, 0, 0);

// Notes section if available
if (!empty($dispensing['notes'])) {
    $pdf->Ln(5);
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->Cell(0, 6, 'Notes:', 0, 1);
    $pdf->SetFont('Arial', '', 9);
    $pdf->MultiCell(0, 5, $dispensing['notes'], 1);
}

// Important notice for insurance payments
if ($dispensing['payment_method'] === 'INSURANCE' && $dispensing['payment_status'] === 'PENDING') {
    $pdf->Ln(5);
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetFillColor(255, 243, 205);
    $pdf->MultiCell(0, 6, 'IMPORTANT: This is a provisional invoice. Payment is pending insurance processing and reconciliation. The patient should present this document to their insurance provider.', 1, 'L', true);
}

// Footer section
$pdf->Ln(10);
$pdf->SetFont('Arial', 'I', 9);
$pdf->SetTextColor(128, 128, 128);
$pdf->MultiCell(0, 5, "This is a computer-generated document. No signature is required.\nFor any queries, please contact the pharmacy department.", 0, 'C');

// Output PDF
$pdf->Output('D', 'Dispensing_Invoice_' . $dispensing['dispensing_number'] . '.pdf');
?>