<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/BuyerSystem.php';

if (!isLoggedIn() || getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();
$buyerSystem = new BuyerSystem($database, $currentUserId);

if (!$buyerSystem->hasPermission('request_quotes')) {
    $_SESSION['flash_message'] = 'You do not have permission to request quotes. Please upgrade your account.';
    $_SESSION['flash_type'] = 'warning';
    header('Location: ' . APP_URL . '/buyer/dashboard.php');
    exit();
}

// Handle new request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_request') {
    $result = $buyerSystem->requestQuote(
        $_POST['product_type'],
        $_POST['quantity'],
        $_POST['specifications'],
        $_POST['delivery_date']
    );
    
    $_SESSION['flash_message'] = $result['message'];
    $_SESSION['flash_type'] = $result['success'] ? 'success' : 'error';
    header('Location: ' . APP_URL . '/buyer/purchase-requests.php');
    exit();
}

// Get requests
$sql = "SELECT pr.*, 
               (SELECT COUNT(*) FROM quote_responses WHERE request_id = pr.id) as quote_count
        FROM purchase_requests pr
        WHERE pr.buyer_id = ?
        ORDER BY pr.created_at DESC";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$requests = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Purchase Requests';
$breadcrumbs = [['title' => 'Purchase Requests', 'url' => '']];

require_once __DIR__ . '/includes/base.php';
renderBuyerHeader($pageTitle, $breadcrumbs);
?>

<div class="row mb-4">
    <div class="col">
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createRequestModal">
            <i class="bi bi-plus-circle me-2"></i>New Quote Request
        </button>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0"><i class="bi bi-file-text me-2"></i>My Requests (<?php echo count($requests); ?>)</h5>
    </div>
    <div class="card-body">
        <?php if (empty($requests)): ?>
            <div class="text-center py-5">
                <i class="bi bi-inbox" style="font-size: 4rem; color: #d1d5db;"></i>
                <h5 class="mt-3 text-muted">No requests yet</h5>
                <p class="text-muted">Create your first quote request</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>Product Type</th>
                            <th>Quantity</th>
                            <th>Delivery Date</th>
                            <th>Status</th>
                            <th>Quotes</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($requests as $request): ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($request['product_type']); ?></strong></td>
                            <td><?php echo number_format($request['quantity'], 2); ?> <?php echo htmlspecialchars($request['unit']); ?></td>
                            <td><?php echo date('M j, Y', strtotime($request['required_delivery_date'])); ?></td>
                            <td>
                                <?php
                                $badges = [
                                    'pending' => '<span class="badge bg-warning">Pending</span>',
                                    'quoted' => '<span class="badge bg-info">Quoted</span>',
                                    'accepted' => '<span class="badge bg-success">Accepted</span>',
                                    'rejected' => '<span class="badge bg-danger">Rejected</span>'
                                ];
                                echo $badges[$request['status']] ?? $badges['pending'];
                                ?>
                            </td>
                            <td><span class="badge bg-primary"><?php echo $request['quote_count']; ?></span></td>
                            <td><small><?php echo timeAgo($request['created_at']); ?></small></td>
                            <td>
                                <a href="<?php echo APP_URL; ?>/buyer/request-details.php?id=<?php echo $request['id']; ?>" 
                                   class="btn btn-sm btn-outline-primary">
                                    <i class="bi bi-eye"></i> View
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Create Request Modal -->
<div class="modal fade" id="createRequestModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-file-plus me-2"></i>Create Quote Request</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="create_request">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Product Type <span class="text-danger">*</span></label>
                            <input type="text" name="product_type" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Quantity <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" name="quantity" class="form-control" required>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Specifications</label>
                            <textarea name="specifications" class="form-control" rows="3"></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Required Delivery Date <span class="text-danger">*</span></label>
                            <input type="date" name="delivery_date" class="form-control" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-send me-2"></i>Submit Request
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php renderBuyerFooter(); ?>