<?php
include 'config.php';
if(!isset($_SESSION['user_id'])) exit();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $ticket_id = (int)$_POST['ticket_id'];
    $agency_id = $_SESSION['agency_id'];
    $seats     = (int)$_POST['seats'];

    // 1. Fetch Details for Email
    $agency_res = $conn->query("SELECT * FROM agencies WHERE id = $agency_id");
    $agency = $agency_res->fetch_assoc();

    $deal_res = $conn->query("SELECT g.*, a.name as airline_name FROM group_tickets g JOIN airlines a ON g.airline_id = a.id WHERE g.id = $ticket_id");
    $deal = $deal_res->fetch_assoc();

    // 2. Save Request to Database
    $stmt = $conn->prepare("INSERT INTO group_requests (ticket_id, agency_id, requested_seats) VALUES (?, ?, ?)");
    $stmt->bind_param("iii", $ticket_id, $agency_id, $seats);

    if ($stmt->execute()) {
        
        // 3. SEND EMAIL NOTIFICATION
        $to = "tztravelandtours2@gmail.com";
        $subject = "NEW B2B BOOKING REQUEST: " . $agency['agency_name'];
        
        $message = "
        <html>
        <head><title>Booking Request</title></head>
        <body>
            <h2>New Group Ticket Request</h2>
            <p><strong>AGENCY DETAILS:</strong></p>
            <ul>
                <li><strong>Agency:</strong> {$agency['agency_name']}</li>
                <li><strong>Contact Person:</strong> {$agency['owner_name']}</li>
                <li><strong>Email:</strong> {$agency['email']}</li>
                <li><strong>Phone:</strong> {$agency['phone']}</li>
            </ul>
            <hr>
            <p><strong>TICKET DETAILS:</strong></p>
            <ul>
                <li><strong>Airline:</strong> {$deal['airline_name']}</li>
                <li><strong>Route:</strong> {$deal['route']}</li>
                <li><strong>Travel Date:</strong> {$deal['travel_date']}</li>
                <li><strong>Trip Type:</strong> {$deal['trip_type']}</li>
                <li><strong>Requested Seats:</strong> $seats</li>
                <li><strong>Amount per Seat:</strong> PKR " . number_format($deal['price_per_seat']) . "</li>
            </ul>
            <p>Go to your Super Admin panel to Approve or Reject this request.</p>
        </body>
        </html>";

        // Headers for HTML Email
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= "From: B2B Portal <portal@yourdomain.com>" . "\r\n";

        // Send Email
        mail($to, $subject, $message, $headers);

        header("Location: marketplace.php?msg=RequestSent");
    } else {
        echo "Error: " . $conn->error;
    }
}
?>