<?php
$search_status = $_GET['status'] ?? '';
$search_date = $_GET['date'] ?? date('Y-m-d');

$where = "WHERE a.visit_type = 'Home'";
$params = [];

if ($search_status) {
    $where .= " AND a.status = ?";
    $params[] = $search_status;
}
if ($search_date) {
    $where .= " AND DATE(a.start_time) = ?";
    $params[] = $search_date;
}

$query = "
    SELECT 
        a.*, 
        p.name as patient_name, p.phone as patient_phone,
        d.name_$lang as doctor_name,
        n.name_$lang as nurse_name
    FROM appointments a
    JOIN patients p ON a.patient_id = p.id
    LEFT JOIN employees d ON a.doctor_id = d.id
    LEFT JOIN employees n ON a.nurse_id = n.id
    $where
    ORDER BY a.start_time ASC
";

$stmt = $db->prepare($query);
$stmt->execute($params);
$appointments = $stmt->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="fw-bold text-secondary"><i class="bi bi-house-heart me-2"></i><?php echo __('home_visits'); ?></h3>
    <a href="appointments.php" class="btn btn-outline-primary">
        <i class="bi bi-calendar-check me-1"></i> <?php echo __('appointments'); ?>
    </a>
</div>

<!-- Filters -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <form class="row g-3" method="GET">
            <div class="col-md-4">
                <label class="form-label small text-muted"><?php echo __('date'); ?></label>
                <input type="date" name="date" class="form-control" value="<?php echo htmlspecialchars($search_date); ?>" onchange="this.form.submit()">
            </div>
            <div class="col-md-4">
                <label class="form-label small text-muted"><?php echo __('status'); ?></label>
                <select name="status" class="form-select" onchange="this.form.submit()">
                    <option value=""><?php echo __('all'); ?></option>
                    <option value="Scheduled" <?php echo $search_status === 'Scheduled' ? 'selected' : ''; ?>><?php echo __('scheduled'); ?></option>
                    <option value="Completed" <?php echo $search_status === 'Completed' ? 'selected' : ''; ?>><?php echo __('completed'); ?></option>
                    <option value="Cancelled" <?php echo $search_status === 'Cancelled' ? 'selected' : ''; ?>><?php echo __('cancelled'); ?></option>
                </select>
            </div>
        </form>
    </div>
</div>

<div class="row">
    <?php if (empty($appointments)): ?>
        <div class="col-12 text-center py-5">
            <i class="bi bi-house-slash display-4 text-muted mb-3 d-block"></i>
            <p class="text-muted"><?php echo __('no_appointments_found'); ?></p>
        </div>
    <?php else: ?>
        <?php foreach ($appointments as $app): ?>
            <div class="col-md-6 col-lg-4 mb-4">
                <div class="card shadow-sm border-0 h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-3">
                            <span class="badge <?php echo $app['status'] === 'Completed' ? 'bg-success' : ($app['status'] === 'Cancelled' ? 'bg-danger' : 'bg-primary'); ?>">
                                <?php echo __(strtolower($app['status'])); ?>
                            </span>
                            <small class="text-muted fw-bold">
                                <?php echo date('H:i', strtotime($app['start_time'])); ?>
                            </small>
                        </div>
                        
                        <h5 class="card-title mb-1"><?php echo htmlspecialchars($app['patient_name']); ?></h5>
                        <p class="text-muted small mb-3">
                            <i class="bi bi-telephone me-1"></i> <?php echo htmlspecialchars($app['patient_phone']); ?>
                        </p>

                        <div class="mb-3 p-2 bg-light rounded small">
                            <i class="bi bi-geo-alt text-danger me-1"></i> 
                            <?php echo nl2br(htmlspecialchars($app['address'] ?? __('no_address_provided'))); ?>
                        </div>

                        <div class="d-flex align-items-center mb-3">
                            <div class="avatar me-2 bg-secondary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px;">
                                <i class="bi bi-person-fill"></i>
                            </div>
                            <div>
                                <small class="d-block text-muted"><?php echo __('provider'); ?></small>
                                <span class="fw-bold text-dark">
                                    <?php 
                                    if ($app['doctor_id']) {
                                        echo htmlspecialchars($app['doctor_name']) . ' (' . __('doctor') . ')';
                                    } elseif ($app['nurse_id']) {
                                        echo htmlspecialchars($app['nurse_name']) . ' (' . __('nurse') . ')';
                                    } else {
                                        echo '<span class="text-danger">' . __('unassigned') . '</span>';
                                    }
                                    ?>
                                </span>
                            </div>
                        </div>
                        
                        <?php if ($app['reason']): ?>
                            <p class="small text-muted mb-0">
                                <strong><?php echo __('reason_label'); ?>:</strong> <?php echo htmlspecialchars($app['reason']); ?>
                            </p>
                        <?php endif; ?>
                    </div>
                    <div class="card-footer bg-white border-top-0 d-flex justify-content-end gap-2">
                         <!-- Actions -->
                         <?php if ($app['status'] === 'Scheduled'): ?>
                            <button class="btn btn-sm btn-outline-success" onclick="completeHomeVisit(<?php echo $app['id']; ?>, <?php echo $app['patient_id']; ?>, <?php echo $app['doctor_id'] ?: 'null'; ?>, <?php echo $app['nurse_id'] ?: 'null'; ?>)">
                                <i class="bi bi-check2-circle"></i> <?php echo __('complete'); ?>
                            </button>
                         <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- Complete Home Visit Modal -->
<div class="modal fade" id="completeHomeVisitModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo __('complete_home_visit'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="completeVisitForm">
                    <input type="hidden" id="chv_appointment_id" name="appointment_id">
                    <input type="hidden" id="chv_patient_id" name="patient_id">
                    <input type="hidden" id="chv_doctor_id" name="doctor_id">
                    <input type="hidden" id="chv_nurse_id" name="nurse_id">
                    
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('notes_treatment'); ?></label>
                        <textarea class="form-control" id="chv_treatment_plan" name="treatment_plan" rows="3"></textarea>
                    </div>

                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="chv_create_bill" checked>
                        <label class="form-check-label" for="chv_create_bill">
                            <?php echo __('create_bill'); ?>?
                        </label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('close'); ?></button>
                <button type="button" class="btn btn-primary" onclick="submitHomeVisitCompletion()"><?php echo __('save_complete'); ?></button>
            </div>
        </div>
    </div>
</div>

<script>
function completeHomeVisit(aptId, patientId, doctorId, nurseId) {
    document.getElementById('chv_appointment_id').value = aptId;
    document.getElementById('chv_patient_id').value = patientId;
    document.getElementById('chv_doctor_id').value = doctorId || '';
    document.getElementById('chv_nurse_id').value = nurseId || '';
    
    var modal = new bootstrap.Modal(document.getElementById('completeHomeVisitModal'));
    modal.show();
}

function submitHomeVisitCompletion() {
    var aptId = document.getElementById('chv_appointment_id').value;
    var patientId = document.getElementById('chv_patient_id').value;
    var doctorId = document.getElementById('chv_doctor_id').value;
    var nurseId = document.getElementById('chv_nurse_id').value;
    var treatment = document.getElementById('chv_treatment_plan').value;
    var createBill = document.getElementById('chv_create_bill').checked ? '1' : '0';
    
    var form = document.createElement('form');
    form.method = 'POST';
    form.action = 'index.php?page=home_visits'; 
    
    var inputs = [
        {name: 'action', value: 'record_visit'},
        {name: 'patient_id', value: patientId},
        {name: 'doctor_id', value: doctorId},
        {name: 'nurse_id', value: nurseId}, 
        {name: 'appointment_id', value: aptId},
        {name: 'visit_type', value: 'Home'},
        {name: 'treatment_plan', value: treatment},
        {name: 'create_bill', value: createBill}
    ];
    
    inputs.forEach(function(i) {
        if (i.value) {
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = i.name;
            input.value = i.value;
            form.appendChild(input);
        }
    });
    
    document.body.appendChild(form);
    form.submit();
}
</script>