<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) { header("Location: login.php"); exit(); }
include '../db_connect.php';
require('fpdf/fpdf.php'); // Load PDF Library

$msg = "";

if (isset($_POST['save_entry'])) {
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $doctor = $_POST['doctor'];
    $fee = $_POST['fee'];
    $date = date('Y-m-d');
    
    // 1. Generate PDF Filename
    $receipt_no = time();
    $filename = "Receipt_" . $receipt_no . ".pdf";
    $filepath = "../assets/receipts/" . $filename;
    $webpath = "https://aasthapadghanhospital.com/assets/receipts/" . $filename; // CHANGE DOMAIN IF NEEDED

    // 2. Create PDF using FPDF
    $pdf = new FPDF();
    $pdf->AddPage();
    
    // Header
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(190,10,'Aastha Padghan Hospital',0,1,'C');
    $pdf->SetFont('Arial','',10);
    $pdf->Cell(190,5,'Padghan Surgical Hospital, Chikhli',0,1,'C');
    $pdf->Cell(190,5,'Phone: +91 9922346009',0,1,'C');
    $pdf->Line(10, 30, 200, 30);
    
    // Receipt Details
    $pdf->Ln(10);
    $pdf->SetFont('Arial','B',14);
    $pdf->Cell(190,10,'OPD RECEIPT',0,1,'C');
    
    $pdf->Ln(5);
    $pdf->SetFont('Arial','',12);
    
    $pdf->Cell(50,10,'Receipt No:',0,0);
    $pdf->Cell(100,10,$receipt_no,0,1);
    
    $pdf->Cell(50,10,'Date:',0,0);
    $pdf->Cell(100,10,$date,0,1);
    
    $pdf->Cell(50,10,'Patient Name:',0,0);
    $pdf->Cell(100,10,$name,0,1);
    
    $pdf->Cell(50,10,'Mobile:',0,0);
    $pdf->Cell(100,10,$phone,0,1);
    
    $pdf->Cell(50,10,'Doctor:',0,0);
    $pdf->Cell(100,10,$doctor,0,1);
    
    // Fees Box
    $pdf->Ln(10);
    $pdf->SetFillColor(230,230,230);
    $pdf->Cell(140,10,'Description',1,0,'C',true);
    $pdf->Cell(50,10,'Amount (INR)',1,1,'C',true);
    
    $pdf->Cell(140,10,'Consultation Fees',1,0);
    $pdf->Cell(50,10,$fee . '/-',1,1,'R');
    
    $pdf->SetFont('Arial','B',12);
    $pdf->Cell(140,10,'Total Paid',1,0,'R');
    $pdf->Cell(50,10,$fee . '/-',1,1,'R');
    
    // Footer
    $pdf->Ln(20);
    $pdf->SetFont('Arial','I',10);
    $pdf->Cell(190,10,'(This is a computer generated receipt)',0,1,'C');
    
    // Save to Server
    $pdf->Output('F', $filepath);

    // 3. Insert into Database
    $stmt = $conn->prepare("INSERT INTO patient_entries (patient_name, phone, email, doctor, visit_date, consultation_fee, pdf_file) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssis", $name, $phone, $email, $doctor, $date, $fee, $filename);
    
    if ($stmt->execute()) {
        // 4. Send Email
        if(!empty($email)) {
            $subject = "Your OPD Receipt - Aastha Hospital";
            $message = "Dear $name,\n\nThank you for visiting Aastha Padghan Medical.\n\nYour appointment with $doctor is confirmed.\n\nYou can download your receipt here:\n$webpath\n\nRegards,\nAastha Hospital Team";
            $headers = "From: no-reply@aasthapadghanhospital.com";
            
            mail($email, $subject, $message, $headers);
            $msg = "Entry Saved, PDF Generated & Email Sent!";
        } else {
            $msg = "Entry Saved & PDF Generated (No Email provided).";
        }
    } else {
        $msg = "Error: " . $conn->error;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Patient Entry</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 p-6">
    <nav class="mb-6 flex gap-4">
        <a href="dashboard.php" class="text-blue-600 font-bold">← Back to Dashboard</a>
    </nav>

    <div class="grid md:grid-cols-2 gap-8">
        
        <div class="bg-white p-6 rounded shadow-md border-t-4 border-teal-600">
            <h2 class="text-xl font-bold mb-4">🏥 New Patient Entry</h2>
            <?php if($msg) echo "<p class='bg-green-100 text-green-700 p-3 rounded mb-4'>$msg</p>"; ?>
            
            <form method="POST">
                <div class="grid grid-cols-2 gap-4">
                    <div class="mb-4">
                        <label class="block text-sm text-gray-600">Patient Name</label>
                        <input type="text" name="name" required class="w-full border p-2 rounded">
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm text-gray-600">Phone</label>
                        <input type="number" name="phone" required class="w-full border p-2 rounded">
                    </div>
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm text-gray-600">Email (Optional - for Receipt)</label>
                    <input type="email" name="email" placeholder="customer@example.com" class="w-full border p-2 rounded">
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div class="mb-4">
                        <label class="block text-sm text-gray-600">Select Doctor</label>
                        <select name="doctor" class="w-full border p-2 rounded">
                            <option value="Dr. Gajanan Padghan">Dr. Gajanan Padghan</option>
                            <option value="Dr. Anita Padghan">Dr. Anita Padghan</option>
                        </select>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm text-gray-600">Consultation Fee (₹)</label>
                        <input type="number" name="fee" value="500" required class="w-full border p-2 rounded">
                    </div>
                </div>
                
                <button type="submit" name="save_entry" class="w-full bg-teal-600 text-white font-bold py-3 rounded hover:bg-teal-700">
                    Generate Receipt & Send Email
                </button>
            </form>
        </div>

        <div class="bg-white p-6 rounded shadow-md">
            <h2 class="text-xl font-bold mb-4">Recent Entries</h2>
            <div class="overflow-y-auto h-96">
                <?php
                $res = $conn->query("SELECT * FROM patient_entries ORDER BY id DESC LIMIT 10");
                while($row = $res->fetch_assoc()) {
                    echo '<div class="border-b py-3 flex justify-between items-center">';
                    echo '<div>';
                    echo '<p class="font-bold text-gray-800">' . $row['patient_name'] . '</p>';
                    echo '<p class="text-xs text-gray-500">' . $row['doctor'] . ' | ' . $row['visit_date'] . '</p>';
                    echo '</div>';
                    echo '<div>';
                    echo '<a href="../assets/receipts/' . $row['pdf_file'] . '" target="_blank" class="bg-red-500 text-white text-xs px-3 py-1 rounded hover:bg-red-600">View PDF</a>';
                    echo '</div>';
                    echo '</div>';
                }
                ?>
            </div>
        </div>

    </div>
</body>
</html>