<?php
/**
 * View Quotation - Display in the format shown in the picture
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once dirname(__DIR__) . '/config/init.php';
require_auth();

$page_title = 'View Quotation';

// Get quotation ID from URL
$quotation_id = $_GET['id'] ?? 0;

// Fetch quotation details
$quotation = db_fetch_one("
    SELECT q.*, u.username as created_by_name
    FROM quotations q
    LEFT JOIN users u ON q.created_by = u.user_id
    WHERE q.quotation_id = ?
", [$quotation_id]);

if (!$quotation) {
    header("Location: index.php?error=notfound");
    exit;
}

// Fetch quotation items
$items = db_fetch_all("
    SELECT * FROM quotation_items 
    WHERE quotation_id = ?
    ORDER BY item_id
", [$quotation_id]) ?: [];

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    try {
        db_update('quotations', 
            ['status' => $_POST['status']], 
            'quotation_id = ?', 
            [$quotation_id]
        );
        $success = "Status updated successfully";
        // Refresh data
        $quotation = db_fetch_one("SELECT * FROM quotations WHERE quotation_id = ?", [$quotation_id]);
    } catch (Exception $e) {
        $error = "Error updating status: " . $e->getMessage();
    }
}

// Include header
include dirname(__DIR__) . '/views/partials/header.php';
?>

<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Quotation Details</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                        <li class="breadcrumb-item"><a href="index.php">Quotations</a></li>
                        <li class="breadcrumb-item active">View</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <?php if (isset($success)): ?>
                <div class="alert alert-success"><?php echo $success; ?></div>
            <?php endif; ?>
            
            <?php if (isset($error)): ?>
                <div class="alert alert-danger"><?php echo $error; ?></div>
            <?php endif; ?>

            <!-- Action Buttons -->
            <div class="row mb-3">
                <div class="col-12">
                    <div class="btn-group">
                        <a href="edit.php?id=<?php echo $quotation_id; ?>" class="btn btn-primary">
                            <i class="fas fa-edit"></i> Edit
                        </a>
                        <a href="print.php?id=<?php echo $quotation_id; ?>" class="btn btn-secondary" target="_blank">
                            <i class="fas fa-print"></i> Print
                        </a>
                        <a href="pdf.php?id=<?php echo $quotation_id; ?>" class="btn btn-danger">
                            <i class="fas fa-file-pdf"></i> PDF
                        </a>
                        <a href="email.php?id=<?php echo $quotation_id; ?>" class="btn btn-info">
                            <i class="fas fa-envelope"></i> Email
                        </a>
                        <a href="index.php" class="btn btn-default">
                            <i class="fas fa-arrow-left"></i> Back
                        </a>
                    </div>
                    
                    <!-- Status Update Form -->
                    <form method="POST" class="float-right">
                        <div class="input-group">
                            <select name="status" class="form-control" style="width: 150px;">
                                <option value="draft" <?php echo $quotation['status'] == 'draft' ? 'selected' : ''; ?>>Draft</option>
                                <option value="sent" <?php echo $quotation['status'] == 'sent' ? 'selected' : ''; ?>>Sent</option>
                                <option value="accepted" <?php echo $quotation['status'] == 'accepted' ? 'selected' : ''; ?>>Accepted</option>
                                <option value="expired" <?php echo $quotation['status'] == 'expired' ? 'selected' : ''; ?>>Expired</option>
                                <option value="cancelled" <?php echo $quotation['status'] == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                            </select>
                            <div class="input-group-append">
                                <button type="submit" name="update_status" class="btn btn-success">
                                    Update Status
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Quotation Display - EXACT FORMAT FROM PICTURE -->
            <div class="card">
                <div class="card-body">
                    <!-- Hotel Price Quote Header -->
                    <div class="row mb-4">
                        <div class="col-12 text-center">
                            <h2 class="text-primary">Hotel Proforma Invoice</h2>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-6">
                            <h4>Ruhondo Beach Resort</h4>
                            <p>Lake Ruhondo, Musanze<br>
                            Northern Province, Rwanda<br>
                            TIN: 1234578364</p>
                        </div>
                        <div class="col-6">
                            <p class="text-right">
                                <strong>Date:</strong> <?php echo date('d/m/Y', strtotime($quotation['issue_date'])); ?><br>
                                <strong>Quote #:</strong> <?php echo $quotation['quotation_number']; ?>
                            </p>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <!-- RECEIVER Section - EXACTLY LIKE PICTURE -->
                    <div class="row mb-4">
                        <div class="col-6">
                            <h5>RECEIVER</h5>
                            <h4><?php echo htmlspecialchars($quotation['customer_name']); ?></h4>
                            <p>
                                <?php echo htmlspecialchars($quotation['customer_address_line1'] ?? ''); ?><br>
                                <?php echo htmlspecialchars($quotation['customer_address_line2'] ?? ''); ?><br>
                                <?php if (!empty($quotation['customer_email'])): ?>
                                    Email: <?php echo htmlspecialchars($quotation['customer_email']); ?><br>
                                <?php endif; ?>
                                <?php if (!empty($quotation['customer_phone'])): ?>
                                    Tel: <?php echo htmlspecialchars($quotation['customer_phone']); ?>
                                <?php endif; ?>
                            </p>
                        </div>
                        <div class="col-6">
                            <table class="table table-sm table-borderless text-right">
                                <tr>
                                    <td><strong>Quote Number:</strong></td>
                                    <td><?php echo $quotation['quotation_number']; ?></td>
                                </tr>
                                <tr>
                                    <td><strong>Issue Date:</strong></td>
                                    <td><?php echo date('d M Y', strtotime($quotation['issue_date'])); ?></td>
                                </tr>
                                <tr>
                                    <td><strong>Valid Through:</strong></td>
                                    <td><?php echo date('d M Y', strtotime($quotation['valid_until'])); ?></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    
                    <!-- Items Table - EXACT FORMAT AS PICTURE -->
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped">
                            <thead class="bg-secondary text-white">
                                <tr>
                                    <th>QTY</th>
                                    <th>DESCRIPTION</th>
                                    <th>UNIT PRICE</th>
                                    <th>SUBTOTAL</th>
                                    <th>VAT</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($items as $item): ?>
                                <tr>
                                    <td class="text-center"><?php echo $item['quantity']; ?> Nights</td>
                                    <td><?php echo htmlspecialchars($item['description']); ?></td>
                                    <td class="text-right"><?php echo format_currency($item['unit_price']); ?></td>
                                    <td class="text-right"><?php echo format_currency($item['subtotal']); ?></td>
                                    <td class="text-right"><?php echo format_currency($item['vat_amount']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Notes and Totals - EXACT FORMAT -->
                    <div class="row mt-4">
                        <div class="col-6">
                            <?php if (!empty($quotation['notes'])): ?>
                                <div class="border p-3">
                                    <strong>Notes:</strong><br>
                                    <?php echo nl2br(htmlspecialchars($quotation['notes'])); ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="col-6">
                            <table class="table table-sm table-borderless text-right">
                                <tr>
                                    <td width="50%"><strong>Subtotal:</strong></td>
                                    <td><?php echo format_currency($quotation['subtotal']); ?></td>
                                </tr>
                                <tr>
                                    <td><strong>VAT (<?php echo $quotation['vat_rate']; ?>%):</strong></td>
                                    <td><?php echo format_currency($quotation['vat_amount']); ?></td>
                                </tr>
                                <tr class="h4">
                                    <td><strong>Total:</strong></td>
                                    <td><strong><?php echo format_currency($quotation['total_amount']); ?></strong></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    
                    <!-- Status Badge -->
                    <div class="row mt-3">
                        <div class="col-12 text-right">
                            <span class="badge badge-<?php 
                                echo match($quotation['status']) {
                                    'draft' => 'secondary',
                                    'sent' => 'info',
                                    'accepted' => 'success',
                                    'expired' => 'warning',
                                    'cancelled' => 'danger',
                                    default => 'secondary'
                                };
                            ?> p-3">
                                <h5 class="mb-0">Status: <?php echo ucfirst($quotation['status']); ?></h5>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<?php include dirname(__DIR__) . '/views/partials/footer.php'; ?>