<?php 
if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')) {
    require_once('../../../'.$_REQUEST['tenant'].'/config.php');
}
if(file_exists('/config.php')) {
    require_once('/config.php'); 
}

$surveyorId = $_SESSION['userid'];
$filter = $_POST['filter'] ?? 'today';
$mode = $_POST['mode'] ?? 'assignment';

// Date range filter logic
switch ($filter) {
    case 'today':
        $startDate = strtotime('today midnight');
        $endDate = strtotime('tomorrow midnight') - 1;
        break;
    case 'week':
        $startDate = strtotime('monday this week');
        $endDate = strtotime('sunday this week 23:59:59');
        break;
    case 'month':
        $startDate = strtotime('first day of this month');
        $endDate = strtotime('last day of this month 23:59:59');
        break;
    default:
        $startDate = strtotime('today midnight');
        $endDate = strtotime('tomorrow midnight') - 1;
        break;
}

if ($mode === 'client') {
    // Query to fetch jobs grouped by client while applying the date filters
    $sql = "
        SELECT 
            c.clientname, l.locname, COUNT(i.itemnumber) AS asset_count
        FROM 
            surveyor_assignments sa
        LEFT JOIN 
            itemdetails i ON (sa.site_id = i.locnumber OR sa.asset_id = i.itemnumber)
        LEFT JOIN 
            locations l ON i.locnumber = l.locnumber
        LEFT JOIN
            clientdetails c ON i.clientnumber = c.clientnumber
        WHERE 
            sa.surveyor = ?
            AND i.duedate BETWEEN ? AND ?
            AND sa.status = 1
        GROUP BY 
            c.clientname, l.locname
        ORDER BY 
            c.clientname ASC, l.locname ASC
    ";

    $stmt = $con->prepare($sql);
    $stmt->bind_param('iii', $surveyorId, $startDate, $endDate);
} else {
    // Query to fetch jobs based on assignment with date filters
    $sql = "
        SELECT 
            i.locnumber, i.desc, i.plantnumber, i.serialnumber, i.duedate, l.locname, l.postcode, c.clientname
        FROM 
            surveyor_assignments sa
        LEFT JOIN 
            itemdetails i ON (sa.site_id = i.locnumber OR sa.asset_id = i.itemnumber)
        LEFT JOIN 
            locations l ON i.locnumber = l.locnumber
        LEFT JOIN
            clientdetails c ON i.clientnumber = c.clientnumber
        WHERE 
            sa.surveyor = ? 
            AND i.duedate BETWEEN ? AND ?
            AND sa.status = 1
        ORDER BY 
            i.duedate ASC
    ";

    $stmt = $con->prepare($sql);
    $stmt->bind_param('iii', $surveyorId, $startDate, $endDate);
}

$stmt->execute();
$result = $stmt->get_result();

if ($mode === 'client') {
    // Output for jobs sorted by client
    if ($result->num_rows > 0) {
        echo "<table class='table table-striped'>
                <thead>
                    <tr>
                        <th>Client Name</th>
                        <th>Location Name</th>
                        <th>Assets to Inspect</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>";
        
        while ($row = $result->fetch_assoc()) {
            echo "<tr>
                    <td>{$row['clientname']}</td>
                    <td>{$row['locname']}</td>
                    <td>{$row['asset_count']}</td>
                    <td>
                        <button class='btn btn-info btn-sm' onclick='viewClientJobs(\"{$row['clientname']}\")'>View</button>
                    </td>
                  </tr>";
        }

        echo "</tbody></table>";
    } else {
        echo "<p class='text-center'>No assignments available for this filter.</p>";
    }
} else {
    // Output for jobs by assignment
    if ($result->num_rows > 0) {
        echo "<table class='table table-striped'>
                <thead>
                    <tr>
                        <th></th> <!-- Status Color Column -->
                        <th>Client Name</th>
                        <th>Location Name</th>
                        <th>Postcode</th>
                        <th>Description</th>
                        <th>Plant Number</th>
                        <th>Serial Number</th>
                        <th>Due Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>";

        $today = strtotime('today');
        $thirtyDays = strtotime('+30 days');

        while ($row = $result->fetch_assoc()) {
            $duedate = $row['duedate'];
            $statusClass = '';

            // Determine the status class based on the due date
            if ($duedate < $today) {
                $statusClass = 'status_colour danger-color-dark'; // Overdue
            } elseif ($duedate <= $thirtyDays) {
                $statusClass = 'status_colour warning-color-dark'; // Due within next 30 days
            } else {
                $statusClass = 'status_colour success-color-dark'; // Not due, more than 30 days left
            }

            echo "<tr>
                    <td class='$statusClass' style='width: 10px'></td> <!-- Status Column -->
                    <td>{$row['clientname']}</td>
                    <td>{$row['locname']}</td>
                    <td>{$row['postcode']}</td>
                    <td>{$row['desc']}</td>
                    <td>{$row['plantnumber']}</td>
                    <td>{$row['serialnumber']}</td>
                    <td>" . date('d-m-Y', $duedate) . "</td>
                    <td>
                        <button class='btn btn-info btn-sm' onclick='viewJob({$row['locnumber']})'>View</button>
                        <button class='btn btn-success btn-sm' onclick='markComplete({$row['locnumber']})'>Complete</button>
                    </td>
                  </tr>";
        }

        echo "</tbody></table>";
    } else {
        echo "<p class='text-center'>No assignments available for this filter.</p>";
    }
}

$stmt->close();
$con->close();
?>