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

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

// Check if user is Vendor
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Vendor') {
    header('Location: index.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Get vendor ID
$sql_vendor = "SELECT id FROM vendors WHERE user_id = ?";
$stmt_vendor = $conn->prepare($sql_vendor);
$stmt_vendor->bind_param("i", $user_id);
$stmt_vendor->execute();
$result_vendor = $stmt_vendor->get_result();
$vendor = $result_vendor->fetch_assoc();

if (!$vendor) {
    header('Location: index.php');
    exit();
}

$vendor_id = $vendor['id'];

// Assigned Work Orders
$sql_assigned = "SELECT COUNT(*) as total FROM maintenance_requests 
                 WHERE assigned_vendor_id = ? AND status IN ('Assigned', 'In Progress')";
$stmt_assigned = $conn->prepare($sql_assigned);
$stmt_assigned->bind_param("i", $vendor_id);
$stmt_assigned->execute();
$result_assigned = $stmt_assigned->get_result();
$assigned_jobs = $result_assigned->fetch_assoc()['total'] ?? 0;

// Completed Jobs
$sql_completed = "SELECT COUNT(*) as total FROM maintenance_requests 
                  WHERE assigned_vendor_id = ? AND status = 'Completed'";
$stmt_completed = $conn->prepare($sql_completed);
$stmt_completed->bind_param("i", $vendor_id);
$stmt_completed->execute();
$result_completed = $stmt_completed->get_result();
$completed_jobs = $result_completed->fetch_assoc()['total'] ?? 0;

// Total Earnings
$sql_earnings = "SELECT SUM(final_cost) as total FROM maintenance_requests 
                 WHERE assigned_vendor_id = ? AND status = 'Completed'";
$stmt_earnings = $conn->prepare($sql_earnings);
$stmt_earnings->bind_param("i", $vendor_id);
$stmt_earnings->execute();
$result_earnings = $stmt_earnings->get_result();
$total_earnings = $result_earnings->fetch_assoc()['total'] ?? 0;

// Pending Invoices
$sql_invoices = "SELECT COUNT(*) as total FROM vendor_invoices 
                 WHERE vendor_id = ? AND status = 'pending'";
$stmt_invoices = $conn->prepare($sql_invoices);
$stmt_invoices->bind_param("i", $vendor_id);
$stmt_invoices->execute();
$result_invoices = $stmt_invoices->get_result();
$pending_invoices = $result_invoices->fetch_assoc()['total'] ?? 0;

// Recent Work Orders
$sql_recent = "SELECT mr.*, p.name as property_name, u.unit_number
               FROM maintenance_requests mr
               LEFT JOIN properties p ON mr.property_id = p.id
               LEFT JOIN units u ON mr.unit_id = u.id
               WHERE mr.assigned_vendor_id = ?
               ORDER BY 
                   CASE mr.priority 
                       WHEN 'Emergency' THEN 1 
                       WHEN 'High' THEN 2 
                       WHEN 'Medium' THEN 3 
                       ELSE 4 
                   END, 
                   mr.scheduled_date ASC
               LIMIT 5";
$stmt_recent = $conn->prepare($sql_recent);
$stmt_recent->bind_param("i", $vendor_id);
$stmt_recent->execute();
$result_recent = $stmt_recent->get_result();

// Recent Completed Jobs
$sql_completed_recent = "SELECT mr.*, p.name as property_name, u.unit_number
                         FROM maintenance_requests mr
                         LEFT JOIN properties p ON mr.property_id = p.id
                         LEFT JOIN units u ON mr.unit_id = u.id
                         WHERE mr.assigned_vendor_id = ? AND mr.status = 'Completed'
                         ORDER BY mr.completed_date DESC LIMIT 5";
$stmt_completed_recent = $conn->prepare($sql_completed_recent);
$stmt_completed_recent->bind_param("i", $vendor_id);
$stmt_completed_recent->execute();
$result_completed_recent = $stmt_completed_recent->get_result();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Vendor Dashboard')); ?>
    <?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' => 'Dashboard', 'title' => 'Vendor Dashboard')); ?>

                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Assigned Jobs</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-warning rounded-circle fs-3">
                                                    <i class="ri-briefcase-line text-warning"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                <?php echo number_format($assigned_jobs); ?>
                                            </h4>
                                            <a href="new_work_orders.php" class="text-decoration-underline">View jobs</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Completed</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-success rounded-circle fs-3">
                                                    <i class="ri-checkbox-circle-line text-success"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                <?php echo number_format($completed_jobs); ?>
                                            </h4>
                                            <a href="my_jobs.php" class="text-decoration-underline">View all</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Total Earnings</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-info rounded-circle fs-3">
                                                    <i class="ri-money-dollar-circle-line text-info"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                KES <?php echo number_format($total_earnings, 0); ?>
                                            </h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Pending Invoices</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-danger rounded-circle fs-3">
                                                    <i class="ri-file-list-line text-danger"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                <?php echo number_format($pending_invoices); ?>
                                            </h4>
                                            <a href="vendor_invoices.php" class="text-decoration-underline">View invoices</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Assigned Work Orders</h4>
                                    <a href="new_work_orders.php" class="btn btn-soft-primary btn-sm">View All</a>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Ticket #</th>
                                                    <th>Property/Unit</th>
                                                    <th>Priority</th>
                                                    <th>Scheduled</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_recent && $result_recent->num_rows > 0): ?>
                                                    <?php while($job = $result_recent->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($job['ticket_number'] ?? $job['request_code']); ?></span>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($job['property_name'] ?? 'N/A'); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($job['unit_number'] ?? 'N/A'); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-warning"><?php echo htmlspecialchars($job['priority']); ?></span>
                                                            </td>
                                                            <td>
                                                                <?php if ($job['scheduled_date']): ?>
                                                                    <?php echo date('M d, Y H:i', strtotime($job['scheduled_date'])); ?>
                                                                <?php else: ?>
                                                                    <span class="text-muted">Not scheduled</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php if ($job['status'] == 'Assigned'): ?>
                                                                    <button class="btn btn-primary btn-sm" 
                                                                            onclick="window.location.href='update_maintenance_status.php?id=<?php echo $job['request_id']; ?>&status=In Progress'">
                                                                        <i class="ri-play-line me-1"></i>Start
                                                                    </button>
                                                                <?php elseif ($job['status'] == 'In Progress'): ?>
                                                                    <button class="btn btn-success btn-sm" 
                                                                            onclick="window.location.href='update_maintenance_status.php?id=<?php echo $job['request_id']; ?>&status=Completed'">
                                                                        <i class="ri-check-line me-1"></i>Complete
                                                                    </button>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="5" class="text-center py-4">
                                                            <div class="text-muted">No assigned work orders</div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Recent Completed Jobs</h4>
                                    <a href="my_jobs.php" class="btn btn-soft-primary btn-sm">View All</a>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Ticket #</th>
                                                    <th>Property/Unit</th>
                                                    <th>Completed</th>
                                                    <th>Cost</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_completed_recent && $result_completed_recent->num_rows > 0): ?>
                                                    <?php while($job = $result_completed_recent->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($job['ticket_number'] ?? $job['request_code']); ?></span>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($job['property_name'] ?? 'N/A'); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($job['unit_number'] ?? 'N/A'); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <?php echo $job['completed_date'] ? date('M d, Y', strtotime($job['completed_date'])) : 'N/A'; ?>
                                                            </td>
                                                            <td>
                                                                <?php if ($job['final_cost']): ?>
                                                                    <span class="fw-semibold text-success">KES <?php echo number_format($job['final_cost'], 2); ?></span>
                                                                <?php else: ?>
                                                                    <span class="text-muted">Pending</span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="4" class="text-center py-4">
                                                            <div class="text-muted">No completed jobs</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>
