<?php
session_start();
if (!isset($_SESSION['doctor_logged_in'])) { header("Location: login.php"); exit(); }
include '../db_connect.php';
require('../admin/fpdf/fpdf.php'); 

// 1. Get Patient Details from Queue
if (!isset($_GET['id'])) { die("Invalid Patient ID"); }
$id = intval($_GET['id']);
$patient = $conn->query("SELECT * FROM patient_entries WHERE id=$id")->fetch_assoc();

if (!$patient) { die("Patient not found."); }

// 2. Handle Form Submission
if (isset($_POST['save_rx'])) {
    // Collect Data
    $doctor_name = $_SESSION['doctor_name'] ?? 'Dr. Gajanan Padghan';
    $p_name = $patient['patient_name']; // From DB
    $mobile = $patient['phone'];        // From DB
    
    // Collected from Form
    $age = $_POST['age'];
    $gender = $_POST['gender'];
    $opd = $_POST['opd_number'];
    $symptoms = $_POST['symptoms'];
    $diagnosis = $_POST['diagnosis'];
    $medicines = $_POST['medicines'];
    $advice = $_POST['advice'];
    
    $visit_date_raw = date('Y-m-d'); // Today
    $date_display = date("d/m/Y");
    
    $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']));
    }
    
    // --- GENERATE PDF (Same logic as print_rx.php) ---
    $rx_filename = "RX_" . time() . "_" . $id . ".pdf";
    $filepath = "../assets/receipts/" . $rx_filename;
    
    ob_start();
    $pdf = new FPDF('P','mm','A4');
    $pdf->AddPage();
    
    // Background Image
    $bg_image = '../assets/letterhead.jpg';
    if(file_exists($bg_image)){
        $pdf->Image($bg_image, 0, 0, 210, 297);
    }

    // --- ALIGNMENT SETTINGS (300px Top / Clear Sidebar) ---
    $y_start = 80; // 80mm is approx 300px
    $left_margin = 60;

    // Date (Top Right)
    $pdf->SetFont('Arial','',11);
    $pdf->SetXY(150, $y_start);
    $pdf->Cell(40, 6, 'Date: ' . $date_display, 0, 0, 'R');

    // Patient Details
    $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);
    
    // Line 2: Age / Gender / OPD
    $pdf->SetX($left_margin);
    $pdf->SetFont('Arial','B',11);
    $pdf->Cell(15, 6, 'Info:', 0, 0);
    $pdf->SetFont('Arial','',11);
    $info_text = $age . 'Y / ' . $gender;
    if($opd) $info_text .= '  |  OPD: ' . $opd;
    $pdf->Cell(85, 6, $info_text, 0, 1);

    // Diagnosis
    if($diagnosis) {
        $pdf->Ln(4);
        $pdf->SetX($left_margin);
        $pdf->SetFont('Arial','B',11);
        $pdf->Cell(25, 6, 'Diagnosis:', 0, 0);
        $pdf->SetFont('Arial','',11);
        $pdf->MultiCell(90, 6, $diagnosis);
    }

    // Rx Body (Medicines)
    // Push down by 35mm from start
    $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);
    
    $lines = explode("\n", $medicines);
    foreach($lines as $line) {
        if(trim($line)) {
            $pdf->SetX($left_margin + 5);
            $pdf->Cell(110, 8, '-  ' . trim($line), 0, 1);
        }
    }

    // Advice
    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(110, 6, $advice);
    }

    // Next Visit
    if($next_visit_display) {
        $pdf->SetY(240);
        $pdf->SetX(120);
        $pdf->SetFont('Arial','B',11);
        $pdf->Cell(80, 6, 'Next Visit: ' . $next_visit_display, 0, 0, 'R');
    }

    // Save File
    ob_end_clean();
    $pdf->Output('F', $filepath);

    // --- 3. SAVE TO DATABASE (Dual Entry) ---
    
    // A. Insert into Prescriptions (For History)
    $sql_hist = "INSERT INTO prescriptions (doctor_name, patient_name, age, gender, mobile, opd_number, visit_date, diagnosis, medicine_text, advice, next_visit) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    if($stmt1 = $conn->prepare($sql_hist)) {
        $stmt1->bind_param("ssissssssss", $doctor_name, $p_name, $age, $gender, $mobile, $opd, $visit_date_raw, $diagnosis, $medicines, $advice, $next_visit_db);
        $stmt1->execute();
    }

    // B. Update Patient Queue (Mark Completed)
    $sql_update = "UPDATE patient_entries SET symptoms=?, diagnosis=?, medicines=?, rx_pdf=?, status='Completed' WHERE id=?";
    if($stmt2 = $conn->prepare($sql_update)) {
        $stmt2->bind_param("ssssi", $symptoms, $diagnosis, $medicines, $rx_filename, $id);
        $stmt2->execute();
    }
    
    // Redirect
    echo "<script>
            window.open('../assets/receipts/$rx_filename', '_blank');
            window.location.href = 'dashboard.php';
          </script>";
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Consultation | Dr. Desk</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
    <style>body { font-family: 'Poppins', sans-serif; }</style>
</head>
<body class="bg-gray-100 p-6 min-h-screen">
    
    <div class="max-w-4xl mx-auto bg-white rounded-lg shadow-xl overflow-hidden">
        
        <!-- Header -->
        <div class="bg-teal-900 text-white p-6 flex justify-between items-center">
            <div>
                <h1 class="text-2xl font-bold">Consultation</h1>
                <p class="text-teal-200 text-sm">Patient: <?php echo $patient['patient_name']; ?> | ID: #<?php echo $id; ?></p>
            </div>
            <a href="dashboard.php" class="bg-white text-teal-900 px-4 py-2 rounded font-bold text-sm hover:bg-gray-200 transition">Cancel</a>
        </div>
        
        <!-- Form -->
        <form method="POST" class="p-8 space-y-6">
            
            <!-- Extra Patient Info -->
            <div class="grid grid-cols-3 gap-4 bg-gray-50 p-4 rounded border border-gray-200">
                <div>
                    <label class="block text-xs font-bold text-gray-500 uppercase">Age</label>
                    <input type="number" name="age" required class="w-full border p-2 rounded">
                </div>
                <div>
                    <label class="block text-xs font-bold text-gray-500 uppercase">Gender</label>
                    <select name="gender" class="w-full border p-2 rounded">
                        <option>Male</option>
                        <option>Female</option>
                        <option>Other</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-bold text-gray-500 uppercase">OPD No</label>
                    <input type="text" name="opd_number" class="w-full border p-2 rounded">
                </div>
            </div>

            <div class="grid md:grid-cols-2 gap-6">
                <!-- Symptoms -->
                <div>
                    <label class="block font-bold text-gray-700 mb-2">Symptoms (Complaints)</label>
                    <textarea name="symptoms" rows="3" class="w-full border-2 border-gray-200 p-3 rounded-lg focus:border-teal-500 outline-none transition" placeholder="e.g. Stomach pain..."></textarea>
                </div>
                <!-- Diagnosis -->
                <div>
                    <label class="block font-bold text-gray-700 mb-2">Diagnosis (Findings)</label>
                    <textarea name="diagnosis" rows="3" class="w-full border-2 border-gray-200 p-3 rounded-lg focus:border-teal-500 outline-none transition" placeholder="e.g. Acute Appendicitis"></textarea>
                </div>
            </div>

            <!-- Medicines -->
            <div class="bg-blue-50 p-6 rounded-xl border border-blue-100">
                <label class="block font-bold text-blue-900 mb-2 text-xl flex items-center gap-2">
                    <span>💊</span> Medicines (Rx)
                </label>
                <p class="text-xs text-blue-600 mb-3">Enter each medicine on a new line.</p>
                <textarea name="medicines" rows="10" required class="w-full border-2 border-blue-200 p-4 rounded-lg font-mono text-lg focus:border-blue-500 outline-none shadow-inner" placeholder="Tab Pan 40mg --- 1-0-0 --- 5 Days"></textarea>
            </div>

            <!-- Advice & Follow Up -->
            <div class="grid md:grid-cols-2 gap-6">
                <div>
                    <label class="block font-bold text-gray-700 mb-2">Advice / Instructions</label>
                    <textarea name="advice" rows="2" class="w-full border-2 border-gray-200 p-3 rounded-lg" placeholder="Drink water..."></textarea>
                </div>
                <div>
                    <label class="block font-bold text-gray-700 mb-2">Next Visit Date</label>
                    <input type="date" name="next_visit" class="w-full border-2 border-gray-200 p-3 rounded-lg">
                </div>
            </div>

            <!-- Submit Button -->
            <button type="submit" name="save_rx" class="w-full bg-teal-600 text-white font-bold py-4 rounded-xl text-lg hover:bg-teal-700 shadow-lg transition transform hover:scale-[1.01] flex justify-center items-center gap-3">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2.5 0a.5.5 0 01.5.5v3a.5.5 0 01-.5.5h-6a.5.5 0 01-.5-.5v-3a.5.5 0 01.5-.5h6z"></path></svg>
                Save & Print Prescription
            </button>

        </form>
    </div>

</body>
</html>