<?php
/**
 * DELETE ITEM HANDLER
 * File: vendor/delete-item.php
 * Handle item deletion by vendor
 */

require_once '../app/Core/init.php';

// Require vendor authentication
Auth::requireVendor();

// Check if item ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    flash('error', 'Invalid item ID.', 'danger');
    redirect('items.php');
}

$item_id = (int)$_GET['id'];

// Initialize models
$item = new Item();
$vendor = new Vendor();

// Get vendor details
$vendor_id = Auth::id();
$vendor_data = $vendor->getByUserId($vendor_id);

if (!$vendor_data) {
    flash('error', 'Vendor profile not found.', 'danger');
    redirect('items.php');
}

// Get item details and verify ownership
$item_data = $item->find($item_id);

if (!$item_data) {
    flash('error', 'Item not found.', 'danger');
    redirect('items.php');
}

// Verify vendor owns this item
if ($item_data['vendor_id'] != $vendor_data['id']) {
    flash('error', 'You do not have permission to delete this item.', 'danger');
    redirect('items.php');
}

// Check if item has active orders
$db = Database::getInstance();
$active_orders_sql = "SELECT COUNT(*) as count FROM orders 
                      WHERE item_id = ? AND status IN ('pending', 'confirmed', 'ongoing')";
$active_orders = $db->fetch($active_orders_sql, [$item_id]);

if ($active_orders['count'] > 0) {
    flash('error', 'Cannot delete item with active orders. Please wait until all orders are completed.', 'danger');
    redirect('items.php');
}

// Handle POST request (actual deletion)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token
    if (!Security::validateToken($_POST['csrf_token'] ?? '')) {
        flash('error', 'Invalid security token. Please try again.', 'danger');
        redirect('items.php');
    }
    
    try {
        // Delete the item
        if ($item->delete($item_id)) {
            flash('success', 'Item deleted successfully.', 'success');
        } else {
            flash('error', 'Failed to delete item. Please try again.', 'danger');
        }
    } catch (Exception $e) {
        flash('error', 'Error: ' . $e->getMessage(), 'danger');
    }
    
    redirect('items.php');
}

// Page variables
$page_title = "Delete Item - " . esc($item_data['title']);
$active_menu = "items";

// Include header
include '../templates/layouts/vendor/header.php';
?>

<div class="main-content">
    <div class="page-header">
        <div class="header-left">
            <h1><i class="fas fa-trash"></i> Delete Item</h1>
            <p class="text-muted">Confirm item deletion</p>
        </div>
    </div>

    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header bg-danger text-white">
                    <h5 class="mb-0"><i class="fas fa-exclamation-triangle"></i> Confirm Deletion</h5>
                </div>
                <div class="card-body">
                    <div class="alert alert-warning">
                        <h5><i class="fas fa-exclamation-circle"></i> Warning!</h5>
                        <p class="mb-0">
                            This action cannot be undone. Deleting this item will permanently remove:
                        </p>
                        <ul class="mt-2 mb-0">
                            <li>The item and all its details</li>
                            <li>All item images</li>
                            <li>All reviews and ratings</li>
                            <li>All update history</li>
                        </ul>
                        <p class="mt-2 mb-0">
                            <strong>Note:</strong> Past transactions and orders will be preserved for record-keeping purposes.
                        </p>
                    </div>

                    <!-- Item Preview -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <img src="<?= upload('items/' . $item_data['main_image']) ?>" 
                                         alt="<?= esc($item_data['title']) ?>" 
                                         class="img-fluid rounded">
                                </div>
                                <div class="col-md-8">
                                    <h4><?= esc($item_data['title']) ?></h4>
                                    <p class="text-muted mb-2">
                                        <i class="fas fa-tag"></i> <?= esc($item_data['category_name']) ?>
                                    </p>
                                    <p class="mb-2">
                                        <strong>Price:</strong> <?= format_money($item_data['price_per_day']) ?>/day
                                    </p>
                                    <p class="mb-2">
                                        <strong>Status:</strong> <?= format_status_badge($item_data['approval_status']) ?>
                                    </p>
                                    <p class="mb-2">
                                        <strong>Total Orders:</strong> 
                                        <?php
                                        $total_orders_sql = "SELECT COUNT(*) as count FROM orders WHERE item_id = ?";
                                        $total_orders = $db->fetch($total_orders_sql, [$item_id]);
                                        echo number_format($total_orders['count']);
                                        ?>
                                    </p>
                                    <p class="mb-0">
                                        <strong>Total Reviews:</strong> 
                                        <?php
                                        $total_reviews_sql = "SELECT COUNT(*) as count FROM reviews WHERE item_id = ?";
                                        $total_reviews = $db->fetch($total_reviews_sql, [$item_id]);
                                        echo number_format($total_reviews['count']);
                                        ?>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Confirmation Form -->
                    <form method="POST" action="" id="deleteForm">
                        <?= Security::csrfField() ?>
                        
                        <div class="form-check mb-4">
                            <input class="form-check-input" type="checkbox" id="confirmDelete" required>
                            <label class="form-check-label" for="confirmDelete">
                                I understand that this action is permanent and cannot be undone
                            </label>
                        </div>

                        <div class="d-flex gap-3">
                            <button type="submit" class="btn btn-danger" id="deleteBtn" disabled>
                                <i class="fas fa-trash"></i> Delete Item Permanently
                            </button>
                            <a href="items.php" class="btn btn-secondary">
                                <i class="fas fa-times"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('confirmDelete').addEventListener('change', function() {
    document.getElementById('deleteBtn').disabled = !this.checked;
});

document.getElementById('deleteForm').addEventListener('submit', function(e) {
    if (!confirm('Are you absolutely sure you want to delete this item? This cannot be undone!')) {
        e.preventDefault();
    }
});
</script>

<?php //include '../templates/layouts/vendor/footer.php'; ?>