<?php 
// Advanced Debugging & Config
ini_set('display_errors', 1); error_reporting(E_ALL);
date_default_timezone_set('Asia/Dhaka');
require_once '../db_connect.php'; 

$success_msg = ''; $error_msg = '';

// ==========================================
// 1. UPDATE STATUS & FEEDBACK
// ==========================================
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['review_log'])) {
    $log_id = (int)$_POST['log_id'];
    $status = $_POST['status'];
    $feedback = trim($_POST['feedback']);

    try {
        $stmt = $pdo->prepare("UPDATE hifz_logs SET status = ?, feedback = ? WHERE id = ?");
        $stmt->execute([$status, $feedback, $log_id]);
        $success_msg = "Performance log updated successfully!";
    } catch (Exception $e) { $error_msg = "Database Error."; }
}

// ==========================================
// 2. DELETE LOG
// ==========================================
if (isset($_GET['delete_id'])) {
    try {
        $pdo->prepare("DELETE FROM hifz_logs WHERE id = ?")->execute([$_GET['delete_id']]);
        $success_msg = "Log removed successfully.";
    } catch (Exception $e) { $error_msg = "Error deleting log."; }
}

include 'includes/header.php'; 
include 'includes/sidebar.php'; 

// Fetch All Logs with Student Names
$logs_query = "
    SELECT hl.*, stu.name as student_name, stu.phone as student_phone 
    FROM hifz_logs hl 
    JOIN students stu ON hl.student_id = stu.id 
    ORDER BY hl.log_date DESC, hl.id DESC
";
$hifz_logs = $pdo->query($logs_query)->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    /* Premium Theme Colors */
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }
    .main-content { background-color: var(--bg-soft); min-height: 100vh; padding-bottom: 50px; font-family: 'Outfit', sans-serif; }
    
    /* Header & Mobile Menu */
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 30px; border-left: 6px solid var(--theme-green); }
    #sidebarToggle { display: none; width: 45px; height: 45px; border-radius: 12px; background: #f1f5f9; border: 1px solid #e2e8f0; color: var(--theme-green); cursor: pointer; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; }
    #sidebarToggle:hover { background: var(--theme-green); color: #fff; }

    /* Desktop Table */
    .desktop-table-card { background: #fff; border-radius: 20px; border: 1px solid #e2e8f0; box-shadow: 0 10px 40px rgba(0,0,0,0.02); overflow: hidden; border-top: 5px solid var(--theme-green); }
    .table thead th { background-color: #f1f5f9; color: #64748b; font-size: 11px; text-transform: uppercase; font-weight: 800; padding: 18px 20px; border: none; letter-spacing: 0.5px; }
    .table tbody tr:hover { background-color: #f8fafc; }
    .table td { padding: 15px 20px; vertical-align: middle; font-size: 14px; color: #334155; border-bottom: 1px solid #f1f5f9; }
    
    /* Avatars */
    .avatar-circle { width: 45px; height: 45px; border-radius: 12px; background: rgba(6, 78, 59, 0.1); color: var(--theme-green); display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 18px; flex-shrink: 0; }
    
    /* Badges & Status */
    .status-badge { padding: 6px 14px; border-radius: 8px; font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; display: inline-flex; align-items: center; gap: 4px; }
    .bg-pending { background: #fffbeb; color: #d97706; border: 1px solid #fde68a; }
    .bg-excellent { background: #ecfdf5; color: #10b981; border: 1px solid #a7f3d0; }
    .bg-good { background: #eff6ff; color: #3b82f6; border: 1px solid #bfdbfe; }
    .bg-practice { background: #fef2f2; color: #ef4444; border: 1px solid #fecaca; }
    
    /* Action Buttons */
    .btn-review { background: #f1f5f9; color: var(--theme-green); border: none; padding: 8px 18px; border-radius: 10px; font-weight: 800; font-size: 12px; transition: 0.3s; display: inline-flex; align-items: center; }
    .btn-review:hover { background: var(--theme-green); color: #fff; transform: translateY(-2px); box-shadow: 0 4px 10px rgba(6, 78, 59, 0.2); }
    
    .action-icon { width: 36px; height: 36px; display: inline-flex; align-items: center; justify-content: center; border-radius: 10px; background: #fef2f2; color: #ef4444; transition: 0.3s; text-decoration: none; border: none; margin-left: 5px; }
    .action-icon:hover { background: #ef4444; color: #fff; transform: translateY(-2px); }

    /* Animations */
    .fade-up { animation: fadeInUp 0.4s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(15px); } 100% { opacity: 1; transform: translateY(0); } }

    /* Modals & Inputs */
    .modal-content { border-radius: 24px; border: none; box-shadow: 0 20px 50px rgba(0,0,0,0.1); }
    .modal-header { border-bottom: 1px solid #f1f5f9; padding: 20px 30px; }
    .form-control, .form-select { border-radius: 12px; border: 2px solid #f1f5f9; padding: 12px 15px; font-size: 14px; background: #f8fafc; transition: 0.3s; }
    .form-control:focus, .form-select:focus { border-color: var(--theme-green); background: #fff; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); }

    /* 📱 Mobile Specific Styles (Card View) */
    .hifz-mobile-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow: hidden; transition: 0.3s; }
    
    @media (max-width: 991.98px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { padding: 20px; flex-direction: column; align-items: flex-start !important; gap: 15px; }
        .dashboard-header .header-top { width: 100%; display: flex; justify-content: flex-start; align-items: center; gap: 15px; }
        .header-title { font-size: 1.2rem; }
    }
    @media (min-width: 992px) {
        #sidebarToggle { display: none !important; }
    }
</style>

<div class="main-content p-3 p-md-4">
    
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="header-top">
            <button id="sidebarToggle" class="shadow-sm"><i class="fas fa-bars fs-5"></i></button>
            <div>
                <h4 class="mb-0 fw-bold text-dark header-title"><i class="fas fa-quran me-2" style="color: var(--theme-green);"></i> Hifz Monitoring Desk</h4>
                <p class="text-muted small fw-bold mb-0 d-none d-md-block">Review and grade students' daily Quran memorization</p>
            </div>
        </div>
        <div class="d-none d-md-block">
            <span class="badge bg-light text-dark border px-3 py-2 rounded-pill fw-bold shadow-sm">Total Logs: <?= count($hifz_logs) ?></span>
        </div>
    </div>

    <?php if($success_msg): ?> 
        <div class="alert alert-success d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up" style="border-left: 5px solid #10b981 !important;">
            <i class="fas fa-check-circle me-3 fa-2x text-success"></i> 
            <div><strong class="d-block text-success">Success!</strong><span class="text-muted small"><?= $success_msg ?></span></div>
        </div>
    <?php endif; ?>
    <?php if($error_msg): ?> 
        <div class="alert alert-danger d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up" style="border-left: 5px solid #ef4444 !important;">
            <i class="fas fa-exclamation-triangle me-3 fa-2x text-danger"></i> 
            <div><strong class="d-block text-danger">Error!</strong><span class="text-muted small"><?= $error_msg ?></span></div>
        </div>
    <?php endif; ?>

    <div class="desktop-table-card d-none d-lg-block fade-up" style="animation-delay: 0.1s;">
        <div class="table-responsive">
            <table class="table align-middle mb-0 border-0">
                <thead>
                    <tr>
                        <th class="ps-4">Student & Date</th>
                        <th>Type</th>
                        <th>Lesson Details</th>
                        <th>Review Status</th>
                        <th class="text-end pe-4">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($hifz_logs)): foreach($hifz_logs as $log): 
                        // Status Badge Colors
                        $b_class = 'bg-pending'; $icon = 'fas fa-clock';
                        if($log['status'] == 'Excellent') { $b_class = 'bg-excellent'; $icon = 'fas fa-star'; }
                        elseif($log['status'] == 'Good') { $b_class = 'bg-good'; $icon = 'fas fa-thumbs-up'; }
                        elseif($log['status'] == 'Needs Practice') { $b_class = 'bg-practice'; $icon = 'fas fa-exclamation-circle'; }
                    ?>
                    <tr>
                        <td class="ps-4 py-3">
                            <div class="d-flex align-items-center gap-3">
                                <div class="avatar-circle shadow-sm"><?= strtoupper(substr($log['student_name'], 0, 1)) ?></div>
                                <div>
                                    <div class="fw-bold text-dark" style="font-size: 15px;"><?= htmlspecialchars((string)$log['student_name']) ?></div>
                                    <small class="text-muted fw-bold"><i class="far fa-calendar-alt me-1 text-primary"></i> <?= date('d M, Y', strtotime($log['log_date'])) ?></small>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="badge bg-light text-primary border border-primary-subtle px-3 py-2 rounded-pill fw-bold" style="font-size: 11px;">
                                <?= htmlspecialchars((string)$log['lesson_type']) ?>
                            </span>
                        </td>
                        <td>
                            <div class="fw-bold text-dark mb-1" style="font-size: 14px;"><i class="fas fa-book-open text-muted me-1"></i> <?= htmlspecialchars((string)$log['surah_name']) ?></div>
                            <small class="text-muted fw-bold">Range: <span class="text-dark"><?= htmlspecialchars((string)$log['ayah_range']) ?></span></small>
                        </td>
                        <td>
                            <span class="status-badge <?= $b_class ?> shadow-sm">
                                <i class="<?= $icon ?>"></i> <?= htmlspecialchars((string)$log['status']) ?>
                            </span>
                        </td>
                        <td class="text-end pe-4">
                            <div class="d-flex justify-content-end align-items-center">
                                <button class="btn-review shadow-sm" onclick="openReviewModal('<?= $log['id'] ?>', '<?= addslashes((string)$log['student_name']) ?>', '<?= htmlspecialchars((string)$log['surah_name']) ?>', '<?= (string)$log['status'] ?>', '<?= addslashes((string)$log['feedback']) ?>')" title="Grade Lesson">
                                    <i class="fas fa-marker me-1"></i> REVIEW
                                </button>
                                <a href="?delete_id=<?= $log['id'] ?>" class="action-icon shadow-sm" onclick="return confirm('Delete this log entry?')" title="Delete">
                                    <i class="fas fa-trash-alt"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                        <tr><td colspan="5" class="text-center py-5 text-muted fw-bold"><i class="fas fa-file-alt fa-2x mb-3 opacity-25 d-block"></i> No hifz logs submitted yet.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="d-block d-lg-none fade-up" style="animation-delay: 0.1s;">
        <div class="row g-3">
            <?php if(!empty($hifz_logs)): foreach($hifz_logs as $log): 
                $b_class = 'bg-pending'; $icon = 'fas fa-clock';
                if($log['status'] == 'Excellent') { $b_class = 'bg-excellent'; $icon = 'fas fa-star'; }
                elseif($log['status'] == 'Good') { $b_class = 'bg-good'; $icon = 'fas fa-thumbs-up'; }
                elseif($log['status'] == 'Needs Practice') { $b_class = 'bg-practice'; $icon = 'fas fa-exclamation-circle'; }
            ?>
            <div class="col-12">
                <div class="hifz-mobile-card p-3">
                    <div class="d-flex justify-content-between align-items-start mb-3 pb-3 border-bottom">
                        <div class="d-flex align-items-center gap-3">
                            <div class="avatar-circle shadow-sm" style="width: 45px; height: 45px; font-size: 16px;"><?= strtoupper(substr($log['student_name'], 0, 1)) ?></div>
                            <div>
                                <h6 class="fw-bold text-dark mb-1" style="font-size: 15px;"><?= htmlspecialchars((string)$log['student_name']) ?></h6>
                                <span class="badge bg-light text-primary border border-primary-subtle rounded-pill" style="font-size: 9px; padding: 3px 8px;">
                                    <?= htmlspecialchars((string)$log['lesson_type']) ?>
                                </span>
                            </div>
                        </div>
                        <span class="status-badge <?= $b_class ?> shadow-sm" style="font-size: 9px; padding: 4px 8px;">
                            <i class="<?= $icon ?>"></i>
                        </span>
                    </div>
                    
                    <div class="bg-light p-3 rounded-3 border mb-3">
                        <div class="mb-2 d-flex align-items-center">
                            <i class="far fa-calendar-alt text-primary me-2" style="width: 15px;"></i>
                            <span class="text-dark fw-bold" style="font-size: 12px;"><?= date('d M, Y', strtotime($log['log_date'])) ?></span>
                        </div>
                        <div class="mb-2 d-flex align-items-center">
                            <i class="fas fa-book-open text-muted me-2" style="width: 15px;"></i>
                            <span class="text-dark fw-bold" style="font-size: 13px;"><?= htmlspecialchars((string)$log['surah_name']) ?></span>
                        </div>
                        <div class="d-flex align-items-center">
                            <i class="fas fa-list-ol text-muted me-2" style="width: 15px;"></i>
                            <span class="text-muted fw-bold" style="font-size: 12px;">Ayah Range: <span class="text-dark"><?= htmlspecialchars((string)$log['ayah_range']) ?></span></span>
                        </div>
                    </div>
                    
                    <div class="d-flex gap-2">
                        <button class="btn btn-light border flex-grow-1 fw-bold text-success" style="font-size: 12px; padding: 10px;" onclick="openReviewModal('<?= $log['id'] ?>', '<?= addslashes((string)$log['student_name']) ?>', '<?= htmlspecialchars((string)$log['surah_name']) ?>', '<?= (string)$log['status'] ?>', '<?= addslashes((string)$log['feedback']) ?>')"><i class="fas fa-marker me-1"></i> Grade Review</button>
                        <a href="?delete_id=<?= $log['id'] ?>" class="btn btn-light border fw-bold text-danger" style="font-size: 12px; padding: 10px; width: 45px;" onclick="return confirm('Delete this log?');"><i class="fas fa-trash-alt"></i></a>
                    </div>
                </div>
            </div>
            <?php endforeach; else: ?>
                <div class="col-12 text-center py-5 bg-white rounded-4 border shadow-sm">
                    <i class="fas fa-file-alt fa-3x text-muted opacity-25 mb-3 d-block"></i>
                    <h6 class="fw-bold text-muted">No hifz logs submitted!</h6>
                </div>
            <?php endif; ?>
        </div>
    </div>

</div>

<div class="modal fade" id="reviewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold text-dark"><i class="fas fa-clipboard-check text-success me-2"></i> Lesson Review & Grading</h5>
                <button type="button" class="btn-close shadow-none" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body p-4 row g-4">
                    <input type="hidden" name="log_id" id="modal_log_id">
                    
                    <div class="col-12">
                        <div class="p-3 bg-light rounded-3 border text-center">
                            <small class="text-muted fw-bold text-uppercase d-block mb-1" style="font-size: 10px;">Evaluating Student</small>
                            <h6 id="modal_student_info" class="fw-bold text-dark mb-1" style="font-size: 16px;"></h6>
                            <span id="modal_lesson_info" class="badge bg-primary-subtle text-primary border px-3 py-1 rounded-pill"></span>
                        </div>
                    </div>
                    
                    <div class="col-12">
                        <label class="form-label small fw-bold text-uppercase text-muted">Performance Grade <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-star"></i></span>
                            <select name="status" id="modal_status" class="form-select border-start-0 ps-0 fw-bold text-dark" required>
                                <option value="Excellent">🌟 Excellent (চমৎকার)</option>
                                <option value="Good">👍 Good (ভালো)</option>
                                <option value="Average">😐 Average (মোটামুটি)</option>
                                <option value="Needs Practice">📖 Needs Practice (আরও মেহনত চাই)</option>
                            </select>
                        </div>
                    </div>

                    <div class="col-12">
                        <label class="form-label small fw-bold text-uppercase text-muted">Teacher's Feedback / Instruction</label>
                        <textarea name="feedback" id="modal_feedback" class="form-control border-2 fw-medium" rows="3" placeholder="Write advice or pronunciation tips here..."></textarea>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="submit" name="review_log" class="btn w-100 py-3 fw-bold shadow-sm text-white" style="background: var(--theme-green); border-radius: 12px;">SAVE EVALUATION</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // Sidebar Toggle for Mobile
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const sidebar = document.querySelector('.sidebar') || document.getElementById('sidebarMenu');
                if (sidebar) { sidebar.classList.toggle('active'); }
            });
        }
    });

    // Populate Modal Function
    function openReviewModal(id, name, surah, status, feedback) {
        document.getElementById('modal_log_id').value = id;
        document.getElementById('modal_student_info').innerText = name;
        document.getElementById('modal_lesson_info').innerHTML = "<i class='fas fa-book-open me-1'></i> " + surah;
        document.getElementById('modal_status').value = status;
        document.getElementById('modal_feedback').value = feedback;
        
        new bootstrap.Modal(document.getElementById('reviewModal')).show();
    }
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<?php include 'includes/footer.php'; ?>