<?php
$schedules = isset($schedules) ? $schedules : array();
$stores = isset($stores) ? $stores : array();
?>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h4 class="fw-bold mb-1"><i class="fa-solid fa-calendar-days text-primary me-2"></i>Reminder &amp; Check-In Schedules</h4>
            <p class="text-muted mb-0">Automated recurring checklist schedules pushed to branch staff applications.</p>
        </div>
        <div>
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addScheduleModal">
                <i class="fa-solid fa-plus me-1"></i> Create Scheduled Check-In
            </button>
        </div>
    </div>

    <?php if ($this->session->flashdata('success')): ?>
        <div class="alert alert-success alert-dismissible fade show border-0 shadow-sm" role="alert">
            <i class="fa-solid fa-circle-check me-2"></i><?php echo $this->session->flashdata('success'); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="row g-4">
        <?php if (empty($schedules)): ?>
            <div class="col-12 text-center py-5 text-muted card border-0 shadow-sm rounded-4">
                <i class="fa-solid fa-calendar-xmark fs-1 opacity-25 mb-3 d-block"></i>
                No check-in schedules found. Click "Create Scheduled Check-In" to configure routines.
            </div>
        <?php else: ?>
            <?php foreach ($schedules as $id => $sc): ?>
                <div class="col-lg-6">
                    <div class="card border-0 shadow-sm rounded-4 h-100">
                        <div class="card-header bg-transparent border-0 pt-4 px-4 pb-2">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <h5 class="fw-bold text-dark mb-1"><?php echo htmlspecialchars(isset($sc['title']) ? $sc['title'] : 'Check-In Routine'); ?></h5>
                                    <div class="small text-muted font-monospace">ID: <?php echo htmlspecialchars($id); ?></div>
                                </div>
                                <span class="badge bg-primary bg-opacity-10 text-primary rounded-pill px-3 py-1">
                                    <?php echo ucfirst(isset($sc['status']) ? $sc['status'] : 'pending'); ?>
                                </span>
                            </div>
                        </div>
                        <div class="card-body px-4 pb-4">
                            <div class="row g-2 mb-3 bg-light p-3 rounded-3">
                                <div class="col-6">
                                    <small class="text-muted d-block">Scheduled Time</small>
                                    <span class="fw-semibold text-dark">
                                        <i class="fa-regular fa-clock text-primary me-1"></i>
                                        <?php echo isset($sc['scheduledAt']) ? date('h:i A', $sc['scheduledAt'] / 1000) : 'Daily'; ?>
                                    </span>
                                </div>
                                <div class="col-6">
                                    <small class="text-muted d-block">Created On</small>
                                    <span class="text-dark">
                                        <?php echo isset($sc['createdAt']) ? date('M d, Y', $sc['createdAt'] / 1000) : '-'; ?>
                                    </span>
                                </div>
                            </div>

                            <!-- Tasks Checklist -->
                            <h6 class="fw-bold mb-2 small text-uppercase text-muted">Required Checklist Items (<?php echo isset($sc['tasks']) ? count($sc['tasks']) : 0; ?>)</h6>
                            <?php if (!empty($sc['tasks']) && is_array($sc['tasks'])): ?>
                                <ul class="list-group list-group-flush mb-3">
                                    <?php foreach ($sc['tasks'] as $t): ?>
                                        <li class="list-group-item px-0 py-2 border-light d-flex justify-content-between align-items-center">
                                            <div class="d-flex align-items-center">
                                                <i class="fa-solid fa-circle-check text-success me-2"></i>
                                                <span class="fw-medium small"><?php echo htmlspecialchars(isset($t['taskName']) ? $t['taskName'] : 'Task'); ?></span>
                                            </div>
                                            <span class="badge bg-secondary bg-opacity-10 text-secondary border small">
                                                <i class="fa-solid <?php echo (isset($t['mediaType']) && $t['mediaType'] === 'video') ? 'fa-video' : ((isset($t['mediaType']) && $t['mediaType'] === 'image') ? 'fa-camera' : 'fa-photo-film'); ?> me-1"></i>
                                                <?php echo ucfirst(isset($t['mediaType']) ? $t['mediaType'] : 'both'); ?>
                                            </span>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            <?php endif; ?>

                            <!-- Store Completion Status -->
                            <h6 class="fw-bold mb-2 small text-uppercase text-muted">Store Branch Status</h6>
                            <?php if (!empty($sc['storeStatus']) && is_array($sc['storeStatus'])): ?>
                                <div class="d-flex flex-wrap gap-2">
                                    <?php foreach ($sc['storeStatus'] as $sid => $status): ?>
                                        <?php
                                        $sName = isset($stores[$sid]['name']) ? $stores[$sid]['name'] : substr($sid, 0, 8);
                                        $isComp = strtolower((string)$status) === 'completed';
                                        ?>
                                        <span class="badge <?php echo $isComp ? 'bg-success bg-opacity-10 text-success border-success' : 'bg-warning bg-opacity-10 text-warning border-warning'; ?> border py-2 px-3 rounded-3">
                                            <i class="fa-solid <?php echo $isComp ? 'fa-circle-check' : 'fa-clock'; ?> me-1"></i>
                                            <?php echo htmlspecialchars($sName); ?>: <strong><?php echo ucfirst($status); ?></strong>
                                        </span>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<!-- Modal: Create Scheduled Check-In -->
<div class="modal fade" id="addScheduleModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-0 shadow rounded-4">
            <form action="<?php echo base_url('admin/add_schedule'); ?>" method="post">
                <div class="modal-header border-0 pb-0 px-4 pt-4">
                    <h5 class="modal-title fw-bold"><i class="fa-solid fa-calendar-plus text-primary me-2"></i>Create Scheduled Check-In</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body px-4 py-3">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Schedule Routine Title <span class="text-danger">*</span></label>
                        <input type="text" name="title" class="form-control rounded-3" placeholder="e.g. Evening Hygiene &amp; Safety Check" required>
                    </div>

                    <div class="row g-3 mb-3">
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Scheduled Time</label>
                            <input type="time" name="schedule_time" class="form-control rounded-3" value="18:00">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Target Stores</label>
                            <select name="stores[]" class="form-select rounded-3" multiple required style="min-height: 100px;">
                                <?php foreach ($stores as $sId => $s): ?>
                                    <option value="<?php echo htmlspecialchars($sId); ?>" selected>
                                        <?php echo htmlspecialchars(isset($s['name']) ? $s['name'] : $sId); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted">Hold Ctrl to select multiple stores</small>
                        </div>
                    </div>

                    <!-- Tasks Builder -->
                    <div class="border rounded-3 p-3 bg-light">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <label class="fw-bold mb-0">Checklist Tasks &amp; Evidence Requirements</label>
                            <button type="button" class="btn btn-sm btn-outline-primary" id="btnAddTask">
                                <i class="fa-solid fa-plus me-1"></i> Add Task Item
                            </button>
                        </div>
                        <div id="tasksContainer">
                            <div class="row g-2 mb-2 task-row align-items-center">
                                <div class="col-6">
                                    <input type="text" name="task_name[]" class="form-control form-control-sm rounded-3" value="Toppings Area Cleanliness" placeholder="Task Name" required>
                                </div>
                                <div class="col-4">
                                    <select name="task_media[]" class="form-select form-select-sm rounded-3">
                                        <option value="both" selected>Video or Photo</option>
                                        <option value="video">Video Walkthrough Only</option>
                                        <option value="image">Photo Only</option>
                                    </select>
                                </div>
                                <div class="col-2 text-end">
                                    <button type="button" class="btn btn-sm btn-outline-danger btn-remove-task"><i class="fa-solid fa-xmark"></i></button>
                                </div>
                            </div>
                            <div class="row g-2 mb-2 task-row align-items-center">
                                <div class="col-6">
                                    <input type="text" name="task_name[]" class="form-control form-control-sm rounded-3" value="Kitchen Walkthrough" placeholder="Task Name" required>
                                </div>
                                <div class="col-4">
                                    <select name="task_media[]" class="form-select form-select-sm rounded-3">
                                        <option value="image" selected>Photo Only</option>
                                        <option value="video">Video Walkthrough Only</option>
                                        <option value="both">Video or Photo</option>
                                    </select>
                                </div>
                                <div class="col-2 text-end">
                                    <button type="button" class="btn btn-sm btn-outline-danger btn-remove-task"><i class="fa-solid fa-xmark"></i></button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-0 px-4 pb-4">
                    <button type="button" class="btn btn-light px-4" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary px-4 fw-semibold">Save Schedule</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const btnAddTask = document.getElementById('btnAddTask');
    const tasksContainer = document.getElementById('tasksContainer');

    if (btnAddTask && tasksContainer) {
        btnAddTask.addEventListener('click', function() {
            const div = document.createElement('div');
            div.className = 'row g-2 mb-2 task-row align-items-center';
            div.innerHTML = `
                <div class="col-6">
                    <input type="text" name="task_name[]" class="form-control form-control-sm rounded-3" placeholder="Task Name" required>
                </div>
                <div class="col-4">
                    <select name="task_media[]" class="form-select form-select-sm rounded-3">
                        <option value="both">Video or Photo</option>
                        <option value="video">Video Walkthrough Only</option>
                        <option value="image">Photo Only</option>
                    </select>
                </div>
                <div class="col-2 text-end">
                    <button type="button" class="btn btn-sm btn-outline-danger btn-remove-task"><i class="fa-solid fa-xmark"></i></button>
                </div>
            `;
            tasksContainer.appendChild(div);
        });

        tasksContainer.addEventListener('click', function(e) {
            if (e.target.closest('.btn-remove-task')) {
                const row = e.target.closest('.task-row');
                if (tasksContainer.querySelectorAll('.task-row').length > 1) {
                    row.remove();
                }
            }
        });
    }
});
</script>
