<?php
/**
 * Dozar Records List Page
 * Dozar & Tripper Management System
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/nepali_calendar.php';
require_once __DIR__ . '/../includes/nepali_calendar.php';

$user = getCurrentUser();
$pdo = getPDO();

// Handle delete action
if (isset($_GET['delete']) && (hasRole('admin') || ($user['can_delete'] == 1))) {
    $deleteId = (int)$_GET['delete'];
    error_log("DEBUG: Delete requested for ID: " . $deleteId . ", isAdmin: " . (hasRole('admin') ? 'true' : 'false'));
    if ($deleteId > 0) {
        $stmt = $pdo->prepare("DELETE FROM dozar_records WHERE id = ?");
        $stmt->execute([$deleteId]);
        error_log("DEBUG: Delete executed for ID: " . $deleteId);
        showMessage('Record deleted successfully!', 'success');
    }
}

// Get filter parameters
$projectFilter = '';
$params = [];
if ($user['role'] !== 'admin' && $user['role'] !== 'viewer' && $user['assigned_projects']) {
    $projectIds = explode(',', $user['assigned_projects']);
    $placeholders = implode(',', array_fill(0, count($projectIds), '?'));
    $projectFilter = " AND d.project_id IN ($placeholders)";
    $params = $projectIds;
}

// Get projects for filter dropdown
$projects = [];
$stmt = $pdo->query("SELECT * FROM projects WHERE is_active = 1 ORDER BY project_name");
while ($row = $stmt->fetch()) {
    $projects[$row['id']] = $row['project_name'];
}

// Handle filters
$search = sanitize($_GET['search'] ?? '');
$project_id = sanitize($_GET['project_id'] ?? '');
$date_from = sanitize($_GET['date_from'] ?? '');
$date_to = sanitize($_GET['date_to'] ?? '');

$whereClause = "1=1" . $projectFilter;
if ($search) {
    $whereClause .= " AND (d.vehicle_number LIKE ? OR d.driver_name LIKE ? OR d.work_location LIKE ?)";
    $params = array_merge($params, ["%$search%", "%$search%", "%$search%"]);
}
if ($project_id) {
    $whereClause .= " AND d.project_id = ?";
    $params[] = $project_id;
}
if ($date_from) {
    $whereClause .= " AND d.created_date >= ?";
    $params[] = $date_from;
}
if ($date_to) {
    $whereClause .= " AND d.created_date <= ?";
    $params[] = $date_to;
}

// Get records
$sql = "SELECT d.*, p.project_name, v.vehicle_number, dr.full_name as driver_name, df.entity_name as deployed_name, g.group_name
        FROM dozar_records d
        LEFT JOIN projects p ON d.project_id = p.id
        LEFT JOIN vehicles v ON d.vehicle_id = v.id
        LEFT JOIN drivers dr ON d.driver_id = dr.id
        LEFT JOIN deployed_from df ON d.deployed_from_id = df.id
        LEFT JOIN groups g ON d.group_id = g.id
        WHERE $whereClause
        ORDER BY d.created_date DESC, d.id DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$records = $stmt->fetchAll();

$pageTitle = "Dozar Records";
?>
<?php include __DIR__ . '/../includes/header.php'; ?>

<?php displayMessage(); ?>

<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-truck-monster"></i> Dozar Records</h2>
            <a href="add.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> Add New Record
            </a>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" action="" class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Search</label>
                <input type="text" name="search" class="form-control" placeholder="Vehicle, Driver, Location..." value="<?php echo $search; ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">Project</label>
                <select name="project_id" class="form-select">
                    <option value="">All Projects</option>
                    <?php foreach ($projects as $id => $name): ?>
                    <option value="<?php echo $id; ?>" <?php echo $project_id == $id ? 'selected' : ''; ?>><?php echo $name; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Date From (नेपाली)</label>
                <?php echo nepali_date_picker('date_from', $date_from, '', 'form-control', false); ?>
            </div>
            <div class="col-md-2">
                <label class="form-label">Date To (नेपाली)</label>
                <?php echo nepali_date_picker('date_to', $date_to, '', 'form-control', false); ?>
            </div>
            <div class="col-md-2">
                <label class="form-label">&nbsp;</label>
                <button type="submit" class="btn btn-secondary w-100">
                    <i class="fas fa-search"></i> Filter
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Records Table -->
<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Project</th>
                        <th>Vehicle</th>
                        <th>Driver</th>
                        <th>Deployed From</th>
                        <th>Work Location</th>
                        <th>Hours</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($records)): ?>
                    <tr>
                        <td colspan="8" class="text-center text-muted">No records found</td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($records as $record): ?>
                    <tr>
                        <td><?php echo date_to_nepali($record['created_date']); ?></td>
                        <td><?php echo $record['project_name'] ?? '-'; ?></td>
                        <td><?php echo $record['vehicle_number'] ?? '-'; ?></td>
                        <td><?php echo $record['driver_name'] ?? '-'; ?></td>
                        <td><?php echo $record['deployed_name'] ?? '-'; ?></td>
                        <td><?php echo $record['work_location'] ?? '-'; ?></td>
                        <td><?php echo $record['work_length_hours'] ?? '-'; ?></td>
                        <td>
                            <a href="view.php?id=<?php echo $record['id']; ?>" class="btn btn-sm btn-info" title="View">
                                <i class="fas fa-eye"></i>
                            </a>
                            <a href="edit.php?id=<?php echo $record['id']; ?>" class="btn btn-sm btn-warning" title="Edit">
                                <i class="fas fa-edit"></i>
                            </a>
                            <?php if (hasRole('admin') || ($user['can_delete'] == 1)): ?>
                            <a href="index.php?delete=<?php echo $record['id']; ?>" class="btn btn-sm btn-danger" title="Delete" onclick="return confirm('Are you sure you want to delete this record?')">
                                <i class="fas fa-trash"></i>
                            </a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
