<?php
/**
 * Delete Quotation
 */

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

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

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

// Fetch quotation details
$quotation = db_fetch_one("SELECT * FROM quotations WHERE quotation_id = ?", [$quotation_id]);

if (!$quotation) {
    $_SESSION['error'] = "Quotation not found";
    header("Location: index.php");
    exit;
}

// Check if quotation can be deleted (only draft or expired)
if (!in_array($quotation['status'], ['draft', 'expired', 'cancelled'])) {
    $_SESSION['error'] = "Only draft, expired, or cancelled quotations can be deleted";
    header("Location: view.php?id=" . $quotation_id);
    exit;
}

// Handle confirmation
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        db_begin_transaction();
        
        // Delete quotation items first (foreign key will handle automatically with ON DELETE CASCADE)
        db_query("DELETE FROM quotation_items WHERE quotation_id = ?", [$quotation_id]);
        
        // Delete quotation
        db_query("DELETE FROM quotations WHERE quotation_id = ?", [$quotation_id]);
        
        db_commit();
        
        // Log activity
        $current_user = current_user();
        log_activity($current_user['user_id'], 'delete', 'quotation', $quotation_id, "Deleted quotation {$quotation['quotation_number']}");
        
        $_SESSION['success'] = "Quotation deleted successfully";
        header("Location: index.php");
        exit;
        
    } catch (Exception $e) {
        db_rollback();
        $_SESSION['error'] = "Error deleting 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">Delete 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">Delete</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-danger">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-exclamation-triangle"></i>
                                Confirm Deletion
                            </h3>
                        </div>
                        <div class="card-body">
                            <div class="alert alert-warning">
                                <h5><i class="icon fas fa-ban"></i> Warning!</h5>
                                Are you sure you want to delete this quotation? This action cannot be undone.
                            </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>Issue Date</th>
                                    <td><?php echo date('d M Y', strtotime($quotation['issue_date'])); ?></td>
                                </tr>
                                <tr>
                                    <th>Valid Until</th>
                                    <td><?php echo date('d M Y', strtotime($quotation['valid_until'])); ?></td>
                                </tr>
                                <tr>
                                    <th>Total Amount</th>
                                    <td><?php echo format_currency($quotation['total_amount']); ?></td>
                                </tr>
                                <tr>
                                    <th>Status</th>
                                    <td>
                                        <span class="badge badge-<?php 
                                            echo match($quotation['status']) {
                                                'draft' => 'secondary',
                                                'sent' => 'info',
                                                'accepted' => 'success',
                                                'expired' => 'warning',
                                                'cancelled' => 'danger',
                                                default => 'secondary'
                                            };
                                        ?>"><?php echo ucfirst($quotation['status']); ?></span>
                                    </td>
                                </tr>
                            </table>
                            
                            <form method="POST" class="mt-4">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <div class="text-center">
                                    <button type="submit" class="btn btn-danger btn-lg">
                                        <i class="fas fa-trash"></i> Yes, Delete Permanently
                                    </button>
                                    <a href="view.php?id=<?php echo $quotation_id; ?>" class="btn btn-secondary btn-lg">
                                        <i class="fas fa-times"></i> Cancel
                                    </a>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

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