<?php
// --- 1. ENABLE ERROR REPORTING ---
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
if (!isset($_SESSION['doctor_logged_in'])) { 
    die("Error: You are not logged in."); 
}

include '../db_connect.php';
require('../admin/fpdf/fpdf.php'); 

if (isset($_POST['generate'])) {
    // 1. Collect Data
    $doctor_name = $_SESSION['doctor_name'] ?? 'Dr. Gajanan Padghan';
    $p_name = $_POST['patient_name'];
    $age = $_POST['age'];
    $gender = $_POST['gender'];
    $mobile = $_POST['mobile'];
    $opd = $_POST['opd_number'];
    
    $visit_date_raw = $_POST['visit_date'];
    $date_display = date("d/m/Y", strtotime($visit_date_raw));
    
    $diagnosis = $_POST['diagnosis'];
    $medicines = $_POST['medicine_text'];
    $advice = $_POST['advice'];
    
    $next_visit_display = "";
    $next_visit_db = NULL;
    if(!empty($_POST['next_visit'])) {
        $next_visit_db = $_POST['next_visit'];
        $next_visit_display = date("d/m/Y", strtotime($_POST['next_visit']));
    }

    // 2. Save to Database
    $sql = "INSERT INTO prescriptions (doctor_name, patient_name, age, gender, mobile, opd_number, visit_date, diagnosis, medicine_text, advice, next_visit) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    if($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("ssissssssss", $doctor_name, $p_name, $age, $gender, $mobile, $opd, $visit_date_raw, $diagnosis, $medicines, $advice, $next_visit_db);
        $stmt->execute();
    }

    // 3. Generate PDF
    ob_start();
    $pdf = new FPDF('P','mm','A4');
    $pdf->AddPage();

    // -- A. BACKGROUND IMAGE --
    $bg_image = '../assets/letterhead.jpg';
    if(file_exists($bg_image)){
        $pdf->Image($bg_image, 0, 0, 210, 297);
    }

    // --- B. POSITIONING LOGIC (Updated for 300px Header) ---
    
    // 300px is approx 79-80mm. We set y_start to 80mm.
    $y_start = 80; 
    $left_margin = 60; // Keeps content to the right of the Sidebar

    // -- DATE (Top Right) --
    $pdf->SetFont('Arial','',11);
    $pdf->SetXY(150, $y_start); 
    $pdf->Cell(40, 6, 'Date: ' . $date_display, 0, 0, 'R');

    // -- PATIENT DETAILS --
    // Align Name with the Date line
    $pdf->SetXY($left_margin, $y_start); 
    
    $pdf->SetFont('Arial','B',11);
    $pdf->Cell(15, 6, 'Name:', 0, 0);
    $pdf->SetFont('Arial','',11);
    $pdf->Cell(85, 6, strtoupper($p_name), 0, 1); // New line
    
    // Second line (Age / OPD)
    $pdf->SetX($left_margin);
    $pdf->SetFont('Arial','B',11);
    $pdf->Cell(15, 6, 'Age:', 0, 0);
    $pdf->SetFont('Arial','',11);
    $pdf->Cell(30, 6, $age . ' Yrs / ' . $gender, 0, 0);
    
    $pdf->SetFont('Arial','B',11);
    $pdf->Cell(15, 6, 'OPD:', 0, 0);
    $pdf->SetFont('Arial','',11);
    $pdf->Cell(30, 6, $opd, 0, 1); // New line

    // -- DIAGNOSIS --
    if($diagnosis) {
        $pdf->Ln(4); 
        $pdf->SetX($left_margin);
        $pdf->SetFont('Arial','B',11);
        $pdf->Cell(22, 6, 'Diagnosis:', 0, 0);
        $pdf->SetFont('Arial','I',11);
        $pdf->Cell(100, 6, $diagnosis, 0, 1);
    }

    // -- C. PRESCRIPTION BODY (Rx) --
    // Push down by 35mm from the details section (starts around 115mm total)
    $pdf->SetY($y_start + 35); 
    $pdf->SetX($left_margin); 
    
    $pdf->SetFont('Arial','B',20);
    $pdf->Cell(20, 10, 'Rx', 0, 1); // Rx Symbol
    
    $pdf->SetFont('Arial','',12);
    
    // Medicine List
    $lines = explode("\n", $medicines);
    foreach($lines as $line) {
        if(trim($line)) {
            $pdf->SetX($left_margin + 5); // Indent medicines
            $pdf->Cell(130, 8, '- ' . trim($line), 0, 1);
        }
    }

    // -- D. ADVICE / INSTRUCTIONS --
    if($advice) {
        $pdf->Ln(8);
        $pdf->SetX($left_margin);
        $pdf->SetFont('Arial','B',11);
        $pdf->Cell(130, 6, 'Advice / Instructions:', 0, 1);
        
        $pdf->SetFont('Arial','',11);
        $pdf->SetX($left_margin);
        $pdf->MultiCell(130, 6, $advice);
    }

    // -- E. NEXT VISIT (Bottom Right) --
    if($next_visit_display) {
        // Position near bottom of page (e.g., 240mm from top)
        $pdf->SetY(240);
        $pdf->SetX(120);
        $pdf->SetFont('Arial','B',11);
        $pdf->Cell(80, 6, 'Next Visit: ' . $next_visit_display, 0, 0, 'R');
    }

    ob_end_clean(); 
    $pdf->Output('I', 'Prescription.pdf'); 
} else {
    echo "Error: Invalid Request.";
}
?>