<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$search = $_GET['search'] ?? '';
$category_filter = $_GET['category'] ?? '';
$status_filter = $_GET['status'] ?? '';

$sql = "SELECT v.*, 
               COUNT(DISTINCT mr.id) as total_jobs,
               COUNT(DISTINCT CASE WHEN mr.status = 'Completed' THEN mr.id END) as completed_jobs,
               AVG(mr.final_cost) as avg_cost
        FROM vendors v
        LEFT JOIN maintenance_requests mr ON v.id = mr.assigned_vendor_id
        WHERE 1=1";

$params = [];
$types = '';

if (!empty($search)) {
    $sql .= " AND (v.company_name LIKE ? OR v.contact_person LIKE ? OR v.email LIKE ? OR v.phone LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ssss';
}

if (!empty($category_filter)) {
    $sql .= " AND v.service_category = ?";
    $params[] = $category_filter;
    $types .= 's';
}

if (!empty($status_filter)) {
    $sql .= " AND v.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

$sql .= " GROUP BY v.id ORDER BY v.company_name ASC";

if (!empty($params)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($sql);
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Vendors')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Maintenance', 'title' => 'Vendors')); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-4">
                                            <label class="form-label">Search</label>
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($search); ?>" 
                                                   placeholder="Search by company name or contact">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Service Category</label>
                                            <select class="form-select" name="category">
                                                <option value="">All Categories</option>
                                                <option value="Plumbing" <?php echo $category_filter == 'Plumbing' ? 'selected' : ''; ?>>Plumbing</option>
                                                <option value="Electrical" <?php echo $category_filter == 'Electrical' ? 'selected' : ''; ?>>Electrical</option>
                                                <option value="HVAC" <?php echo $category_filter == 'HVAC' ? 'selected' : ''; ?>>HVAC</option>
                                                <option value="Cleaning" <?php echo $category_filter == 'Cleaning' ? 'selected' : ''; ?>>Cleaning</option>
                                                <option value="Security" <?php echo $category_filter == 'Security' ? 'selected' : ''; ?>>Security</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" name="status">
                                                <option value="">All Status</option>
                                                <option value="active" <?php echo $status_filter == 'active' ? 'selected' : ''; ?>>Active</option>
                                                <option value="blacklisted" <?php echo $status_filter == 'blacklisted' ? 'selected' : ''; ?>>Blacklisted</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">&nbsp;</label>
                                            <div>
                                                <button type="submit" class="btn btn-primary w-100">
                                                    <i class="ri-search-line me-1"></i>Filter
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">All Vendors</h4>
                                    <div class="flex-shrink-0">
                                        <a href="add_vendor.php" class="btn btn-primary">
                                            <i class="ri-add-line align-bottom me-1"></i>Add Vendor
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Company Name</th>
                                                    <th>Contact Person</th>
                                                    <th>Contact</th>
                                                    <th>Service Category</th>
                                                    <th>Rating</th>
                                                    <th>Jobs</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($vendor = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($vendor['company_name']); ?></span>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($vendor['contact_person'] ?? 'N/A'); ?></td>
                                                            <td>
                                                                <div>
                                                                    <p class="mb-0"><?php echo htmlspecialchars($vendor['email'] ?? 'N/A'); ?></p>
                                                                    <small class="text-muted"><?php echo htmlspecialchars($vendor['phone'] ?? 'N/A'); ?></small>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo htmlspecialchars($vendor['service_category'] ?? 'N/A'); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $rating = $vendor['rating'] ?? 0;
                                                                $full_stars = floor($rating);
                                                                $half_star = ($rating - $full_stars) >= 0.5;
                                                                ?>
                                                                <div class="d-flex align-items-center">
                                                                    <?php for($i = 0; $i < 5; $i++): ?>
                                                                        <?php if ($i < $full_stars): ?>
                                                                            <i class="ri-star-fill text-warning"></i>
                                                                        <?php elseif ($i == $full_stars && $half_star): ?>
                                                                            <i class="ri-star-half-fill text-warning"></i>
                                                                        <?php else: ?>
                                                                            <i class="ri-star-line text-muted"></i>
                                                                        <?php endif; ?>
                                                                    <?php endfor; ?>
                                                                    <span class="ms-1"><?php echo number_format($rating, 1); ?></span>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-success text-success">
                                                                    <?php echo $vendor['completed_jobs'] ?? 0; ?> / <?php echo $vendor['total_jobs'] ?? 0; ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $status_color = ($vendor['status'] ?? 'active') == 'active' ? 'success' : 'danger';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $status_color; ?> text-<?php echo $status_color; ?>">
                                                                    <?php echo ucfirst($vendor['status'] ?? 'active'); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <div class="dropdown">
                                                                    <button class="btn btn-soft-secondary btn-sm dropdown-toggle" 
                                                                            type="button" data-bs-toggle="dropdown">
                                                                        Actions
                                                                    </button>
                                                                    <ul class="dropdown-menu dropdown-menu-end">
                                                                        <li>
                                                                            <a class="dropdown-item" href="vendor_details.php?id=<?php echo $vendor['id']; ?>">
                                                                                <i class="ri-eye-line align-bottom me-2 text-muted"></i>View
                                                                            </a>
                                                                        </li>
                                                                        <li>
                                                                            <a class="dropdown-item" href="add_vendor.php?id=<?php echo $vendor['id']; ?>">
                                                                                <i class="ri-pencil-line align-bottom me-2 text-muted"></i>Edit
                                                                            </a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="8" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-inbox-line fs-48"></i>
                                                                <p class="mt-2">No vendors found</p>
                                                                <a href="add_vendor.php" class="btn btn-primary btn-sm mt-2">
                                                                    <i class="ri-add-line me-1"></i>Add First Vendor
                                                                </a>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
