<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';
require_once 'tcpdf-main/tcpdf.php';
error_reporting(E_ALL); ini_set('display_errors', 1);

$guest_id = intval($_GET['guest_id'] ?? 0);
if(!$guest_id){
    echo "<div class='alert alert-danger'>Invalid guest selected.</div>";
    exit;
}

// Fetch guest info, charges, payments, balance
$guest = $conn->query("
    SELECT g.*, 
           IFNULL(SUM(i.total_amount),0) AS charges,
           IFNULL(SUM(p.amount),0) AS paid,
           IFNULL(SUM(i.total_amount),0) - IFNULL(SUM(p.amount),0) AS balance
    FROM guests g
    LEFT JOIN invoices i ON g.id=i.guest_id
    LEFT JOIN payments p ON g.id=p.guest_id
    WHERE g.id=$guest_id
    GROUP BY g.id
")->fetch_assoc();

if(!$guest){
    echo "<div class='alert alert-danger'>Guest not found.</div>";
    exit;
}

$message = '';
if(isset($_POST['send_reminder'])){
    $subject = $_POST['subject'];
    $body    = $_POST['body'];
    $to      = $guest['email'];

    if(filter_var($to, FILTER_VALIDATE_EMAIL)){

        // Fetch latest stay for this guest
        $stay = $conn->query("
            SELECT s.*, g.name AS guest_name, g.phone,
                   r.room_number, r.room_type, IFNULL(s.locked_room_price, r.price) AS price
            FROM stays s
            JOIN rooms r ON s.room_id=r.id
            JOIN guests g ON s.guest_id=g.id
            WHERE s.guest_id={$guest['id']}
            ORDER BY s.id DESC LIMIT 1
        ")->fetch_assoc();

        if($stay){
            $room_cost = $stay['price'] * $stay['days'];

            // Fetch additional charges
            $charges = $conn->query("SELECT * FROM charges WHERE guest_id={$stay['guest_id']} ORDER BY created_at ASC");
            $service_total = 0; $service_rows = [];
            while($c = $charges->fetch_assoc()){
                $service_rows[] = $c;
                $service_total += $c['amount'];
            }

            $subtotal = $room_cost + $service_total;
            $tax_rate = 0.175;
            $tax_due = $subtotal * $tax_rate;
            $tourism_levy = $subtotal * 0.01;
            $total_bill = $subtotal + $tax_due + $tourism_levy;

            $paid = $conn->query("SELECT SUM(amount) as total FROM payments WHERE guest_id={$stay['guest_id']} AND status='Paid'")->fetch_assoc()['total'] ?? 0;
            $balance = $total_bill - $paid;

            // ===== TCPDF PDF =====
            $pdf = new TCPDF('P','mm','A4',true,'UTF-8',false);
            $pdf->SetMargins(15,20,15);
            $pdf->AddPage();

            // Logo
            $logo = 'assets/logo.png';
            if(file_exists($logo)){
                $pdf->Image($logo,15,10,40);
            }

            // Header text
            $pdf->SetFont('helvetica','B',16);
            $pdf->Cell(0,10,'INVOICE',0,1,'C');
            $pdf->Ln(5);

            // Guest info
            $pdf->SetFont('helvetica','',12);
            $pdf->MultiCell(0,6,"Guest: {$guest['name']}\nPhone: {$guest['phone']}\nOutstanding Balance: ".number_format($guest['balance'],2)." MK\n\n",0,'L');

            // Room + services table
            $tbl = '<table border="1" cellpadding="4">
                <tr bgcolor="#333333" style="color:#fff;">
                    <th>DESCRIPTION</th>
                    <th>UNIT PRICE</th>
                    <th>QTY</th>
                    <th>No of days</th>
                    <th>AMOUNT</th>
                </tr>
                <tr>
                    <td>ROOM ACCOMMODATION</td>
                    <td>'.number_format($stay['price'],2).'</td>
                    <td>1</td>
                    <td>'.$stay['days'].'</td>
                    <td>'.number_format($room_cost,2).'</td>
                </tr>';
            foreach($service_rows as $sr){
                $tbl .= '<tr>
                    <td>'.htmlspecialchars($sr['name']).'</td>
                    <td>'.number_format($sr['amount']/max(1,$sr['quantity']),2).'</td>
                    <td>'.$sr['quantity'].'</td>
                    <td>-</td>
                    <td>'.number_format($sr['amount'],2).'</td>
                </tr>';
            }
            $tbl .= '</table>';
            $pdf->writeHTML($tbl,true,false,false,false,'');

            // Totals
            $pdf->Ln(2);
            $pdf->SetFont('helvetica','B',12);
            $totals = "
Subtotal: ".number_format($subtotal,2)." MK
Tax (17.5%): ".number_format($tax_due,2)." MK
Tourism Levy: ".number_format($tourism_levy,2)." MK
Total Bill: ".number_format($total_bill,2)." MK
Amount Paid: ".number_format($paid,2)." MK
Balance: ".number_format($balance,2)." MK
";
            $pdf->MultiCell(0,6,$totals,0,'R');

            // Banking Details
            $pdf->Ln(5);
            $pdf->SetFont('helvetica','',11);
            $pdf->MultiCell(0,5,"OUR BANKING DETAILS:\nAccount Name: RAMS EXECUTIVE LODGE\nAccount Number: 9100007723188\nBank: STANDARD BANK\n\nFor queries contact: 0993849382 / 0885123456",0,'L');

            // Watermark if fully paid
            if($balance <= 0){
                $pdf->SetAlpha(0.1);
                $pdf->SetFont('helvetica','B',50);
                $pdf->StartTransform();
                $pdf->Rotate(45,105,140);
                $pdf->Text(50,140,'PAID');
                $pdf->StopTransform();
                $pdf->SetAlpha(1);
            }

            $pdf_content = $pdf->Output('', 'S');
        }

        // ===== SEND EMAIL =====
        $boundary = md5(time());
        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "From: RAMS EXECUTIVE LODGE <cloud@gianterp.space>\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";

        $message_body  = "--{$boundary}\r\n";
        $message_body .= "Content-Type: text/html; charset=UTF-8\r\n\r\n";
        $message_body .= nl2br($body) . "\r\n";
        $message_body .= "--{$boundary}\r\n";
        $message_body .= "Content-Type: application/pdf; name=\"invoice.pdf\"\r\n";
        $message_body .= "Content-Transfer-Encoding: base64\r\n";
        $message_body .= "Content-Disposition: attachment; filename=\"invoice.pdf\"\r\n\r\n";
        $message_body .= chunk_split(base64_encode($pdf_content)) . "\r\n";
        $message_body .= "--{$boundary}--";

        if(mail($to,$subject,$message_body,$headers)){
            $message = "<div class='alert alert-success'><i class='fa fa-check-circle'></i> Reminder sent successfully with PDF invoice attached.</div>";
        } else {
            $message = "<div class='alert alert-danger'><i class='fa fa-times-circle'></i> Failed to send email.</div>";
        }

    } else {
        $message = "<div class='alert alert-danger'><i class='fa fa-exclamation-triangle'></i> Guest does not have a valid email.</div>";
    }
}
?>

<div class="container mt-4">
<h4><i class="fa fa-envelope"></i> Send Payment Reminder to <?= htmlspecialchars($guest['name']) ?></h4>

<?php if($message) echo $message; ?>

<div class="alert alert-warning fs-6">
    <strong>Outstanding Balance:</strong> <?= number_format($guest['balance'],2) ?> MK
</div>

<form method="POST" class="row g-3">
    <div class="col-md-12">
        <label>Subject</label>
        <input type="text" name="subject" class="form-control" value="Payment Reminder - RAMS EXECUTIVE LODGE" required>
    </div>
    <div class="col-md-12">
        <label>Message</label>
        <textarea name="body" class="form-control" rows="8" required>
Dear <?= $guest['name'] ?>,

This is a friendly reminder that you have an outstanding balance of <?= number_format($guest['balance'],2) ?> MK for your stay at RAMS EXECUTIVE LODGE. Kindly settle this amount at your earliest convenience.

Thank you.

Best regards,
RAMS EXECUTIVE LODGE Management
        </textarea>
    </div>
    <div class="col-md-3 d-grid">
        <button type="submit" name="send_reminder" class="btn btn-warning"><i class="fa fa-paper-plane"></i> Send Reminder</button>
    </div>
    <div class="col-md-3 d-grid">
        <a href="payments.php" class="btn btn-secondary"><i class="fa fa-arrow-left"></i> Back</a>
    </div>
</form>
</div>

<?php include 'includes/footer.php'; ?>