<?php
/**
 * Approve/Reject Quotation
 */

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

// Check permission
if (!has_permission('quotations.approve')) {
    $_SESSION['error'] = "You don't have permission to approve quotations";
    header("Location: index.php");
    exit;
}

// 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) {
    $_SESSION['error'] = "Quotation not found";
    header("Location: index.php");
    exit;
}

// Handle approval/rejection
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        db_begin_transaction();
        
        $action = $_POST['action'];
        $new_status = ($action === 'approve') ? 'accepted' : 'cancelled';
        $notes = $_POST['approval_notes'] ?? '';
        
        // Update quotation status
        db_update('quotations', 
            [
                'status' => $new_status,
                'notes' => $quotation['notes'] . "\n\nApproval Notes: " . $notes
            ], 
            'quotation_id = ?', 
            [$quotation_id]
        );
        
        // If approved, maybe create a booking or invoice automatically
        if ($action === 'approve' && isset($_POST['create_booking']) && $_POST['create_booking'] == '1') {
            // Create a reservation from the quotation
            $booking_data = [
                'guest_name' => $quotation['customer_name'],
                'guest_email' => $quotation['customer_email'],
                'guest_phone' => $quotation['customer_phone'],
                'check_in' => date('Y-m-d'),
                'check_out' => date('Y-m-d', strtotime('+1 day')),
                'total_amount' => $quotation['total_amount'],
                'status' => 'confirmed',
                'source' => 'quotation',
                'source_id' => $quotation_id
            ];
            
            // Insert into reservations table (adjust table name as needed)
            // db_insert('reservations', $booking_data);
        }
        
        db_commit();
        
        // Log activity
        $current_user = current_user();
        log_activity($current_user['user_id'], $action, 'quotation', $quotation_id, ucfirst($action) . "d quotation {$quotation['quotation_number']}");
        
        $_SESSION['success'] = "Quotation " . ($action === 'approve' ? 'approved' : 'rejected') . " successfully";
        header("Location: view.php?id=" . $quotation_id);
        exit;
        
    } catch (Exception $e) {
        db_rollback();
        $_SESSION['error'] = "Error processing quotation: " . $e->getMessage();
        header("Location: view.php?id=" . $quotation_id);
        exit;
    }
}

// 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">Approve/Reject Quotation</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"><a href="view.php?id=<?php echo $quotation_id; ?>">View</a></li>
                        <li class="breadcrumb-item active">Approve/Reject</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-8 offset-md-2">
                    <div class="card card-warning">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-check-circle"></i>
                                Quotation Approval
                            </h3>
                        </div>
                        <div class="card-body">
                            <div class="alert alert-<?php 
                                echo $quotation['status'] == 'sent' ? 'info' : 'warning'; 
                            ?>">
                                <i class="icon fas fa-info"></i>
                                Current Status: <strong><?php echo ucfirst($quotation['status']); ?></strong>
                                <?php if ($quotation['status'] != 'sent'): ?>
                                <br>Note: Only quotations with status "Sent" can be approved/rejected.
                                <?php endif; ?>
                            </div>
                            
                            <table class="table table-bordered">
                                <tr>
                                    <th style="width: 200px;">Quotation Number</th>
                                    <td><?php echo htmlspecialchars($quotation['quotation_number']); ?></td>
                                </tr>
                                <tr>
                                    <th>Customer</th>
                                    <td><?php echo htmlspecialchars($quotation['customer_name']); ?></td>
                                </tr>
                                <tr>
                                    <th>Total Amount</th>
                                    <td><?php echo format_currency($quotation['total_amount']); ?></td>
                                </tr>
                                <tr>
                                    <th>Valid Until</th>
                                    <td>
                                        <?php echo date('d M Y', strtotime($quotation['valid_until'])); ?>
                                        <?php if (strtotime($quotation['valid_until']) < time()): ?>
                                            <span class="badge badge-warning">Expired</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            </table>
                            
                            <?php if ($quotation['status'] == 'sent'): ?>
                            <form method="POST" class="mt-4">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                
                                <div class="form-group">
                                    <label>Approval Notes</label>
                                    <textarea class="form-control" name="approval_notes" rows="3" placeholder="Enter any notes regarding approval/rejection..."></textarea>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input type="checkbox" class="form-check-input" name="create_booking" id="createBooking" value="1">
                                    <label class="form-check-label" for="createBooking">
                                        Automatically create booking/reservation upon approval
                                    </label>
                                </div>
                                
                                <div class="text-center">
                                    <button type="submit" name="action" value="approve" class="btn btn-success btn-lg" onclick="return confirm('Are you sure you want to approve this quotation?')">
                                        <i class="fas fa-check"></i> Approve Quotation
                                    </button>
                                    <button type="submit" name="action" value="reject" class="btn btn-danger btn-lg" onclick="return confirm('Are you sure you want to reject this quotation?')">
                                        <i class="fas fa-times"></i> Reject Quotation
                                    </button>
                                    <a href="view.php?id=<?php echo $quotation_id; ?>" class="btn btn-secondary btn-lg">
                                        <i class="fas fa-arrow-left"></i> Go Back
                                    </a>
                                </div>
                            </form>
                            <?php else: ?>
                            <div class="text-center mt-4">
                                <a href="view.php?id=<?php echo $quotation_id; ?>" class="btn btn-primary btn-lg">
                                    <i class="fas fa-arrow-left"></i> Back to Quotation
                                </a>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- Quotation Items Summary -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Quotation Items</h3>
                        </div>
                        <div class="card-body p-0">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>QTY</th>
                                        <th>Description</th>
                                        <th>Unit Price</th>
                                        <th>Subtotal</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $items = db_fetch_all("SELECT * FROM quotation_items WHERE quotation_id = ?", [$quotation_id]) ?: [];
                                    foreach ($items as $item): 
                                    ?>
                                    <tr>
                                        <td><?php echo $item['quantity']; ?></td>
                                        <td><?php echo htmlspecialchars($item['description']); ?></td>
                                        <td><?php echo format_currency($item['unit_price']); ?></td>
                                        <td><?php echo format_currency($item['subtotal']); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="3" class="text-right">Subtotal:</th>
                                        <th><?php echo format_currency($quotation['subtotal']); ?></th>
                                    </tr>
                                    <tr>
                                        <th colspan="3" class="text-right">VAT (15%):</th>
                                        <th><?php echo format_currency($quotation['vat_amount']); ?></th>
                                    </tr>
                                    <tr>
                                        <th colspan="3" class="text-right">Total:</th>
                                        <th><?php echo format_currency($quotation['total_amount']); ?></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

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