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

// ==========================================
// 🛠️ DATABASE AUTO-PATCHER: Hifz Logs Table
// ==========================================
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `hifz_logs` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `student_id` int(11) NOT NULL,
        `lesson_type` varchar(100) NOT NULL,
        `surah_name` varchar(255) NOT NULL,
        `ayah_range` varchar(255) NOT NULL,
        `status` varchar(50) DEFAULT 'Pending Review',
        `feedback` text DEFAULT NULL,
        `log_date` date NOT NULL,
        `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
} catch(PDOException $e) {}

include 'includes/user_header.php'; 
if(file_exists('includes/sidebar.php')) { include 'includes/sidebar.php'; } 

$student_id = $_SESSION['student_id'] ?? null;
if (!$student_id) { echo "<script>window.location.href='login.php';</script>"; exit; }

$success = ""; $error = "";

// ==========================================
// ⚙️ HANDLE SUBMISSION
// ==========================================
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $surah = trim($_POST['surah_name']);
    $ayah = trim($_POST['ayah_range']);
    $type = $_POST['lesson_type'];
    $date = date('Y-m-d');

    if (!empty($surah) && !empty($ayah)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO hifz_logs (student_id, lesson_type, surah_name, ayah_range, log_date) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$student_id, $type, $surah, $ayah, $date]);
            $success = "Alhamdulillah! Your lesson has been logged for teacher review.";
        } catch(PDOException $e) { $error = "Database Error."; }
    } else { $error = "Please fill in all fields."; }
}

// ==========================================
// 📊 FETCH ANALYTICS & HISTORY
// ==========================================
// Example: Calculating progress (Simplified)
$stats_stmt = $pdo->prepare("SELECT COUNT(DISTINCT surah_name) as total_surahs FROM hifz_logs WHERE student_id = ? AND status = 'Excellent'");
$stats_stmt->execute([$student_id]);
$stats = $stats_stmt->fetch();

$history_stmt = $pdo->prepare("SELECT * FROM hifz_logs WHERE student_id = ? ORDER BY log_date DESC LIMIT 10");
$history_stmt->execute([$student_id]);
$hifz_logs = $history_stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    :root { --primary: #064e3b; --accent: #d4af37; --bg-color: #f8fafc; }
    .main-content { background-color: var(--bg-color); min-height: 100vh; padding-bottom: 50px; }
    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } }

    /* Modern Card UI */
    .tracker-card { background: #fff; border-radius: 24px; border: none; padding: 30px; box-shadow: 0 10px 35px rgba(0,0,0,0.03); height: 100%; transition: 0.3s; }
    .tracker-card:hover { transform: translateY(-5px); box-shadow: 0 15px 45px rgba(0,0,0,0.06); }
    
    .stat-box { background: linear-gradient(135deg, var(--primary) 0%, #022c22 100%); border-radius: 20px; padding: 25px; color: white; position: relative; overflow: hidden; box-shadow: 0 10px 25px rgba(6,78,59,0.2); }
    .stat-box i.bg-icon { position: absolute; right: -10px; bottom: -10px; font-size: 90px; opacity: 0.1; transform: rotate(-15deg); }
    
    .status-badge { padding: 6px 16px; border-radius: 50px; font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; }
    .bg-pending { background: #fffbeb; color: #d97706; border: 1px solid #fde68a; }
    .bg-excellent { background: #ecfdf5; color: #10b981; border: 1px solid #a7f3d0; }
    .bg-practice { background: #fef2f2; color: #ef4444; border: 1px solid #fecaca; }
    
    .btn-submit { background: var(--primary); color: white; border-radius: 14px; padding: 15px; font-weight: 700; border: none; transition: 0.3s; width: 100%; box-shadow: 0 8px 20px rgba(6,78,59,0.15); }
    .btn-submit:hover { background: #022c22; color: var(--accent); transform: scale(1.02); }

    .form-control, .form-select { border-radius: 12px; padding: 14px; border: 2px solid #f1f5f9; background: #f8fafc; font-weight: 600; }
    .form-control:focus { border-color: var(--primary); background: #fff; box-shadow: none; }

    #sidebarToggle { display: none; }
    @media (max-width: 991.98px) {
        #sidebarToggle { display: inline-flex; align-items: center; justify-content: center; width: 42px; height: 42px; background: #fff; border: 1px solid #ddd; border-radius: 12px; margin-right: 15px; cursor: pointer; color: var(--primary); }
    }
</style>

<div class="main-content p-3 p-md-5">
    <div class="d-flex align-items-center mb-5 fade-up">
        <div id="sidebarToggle" class="shadow-sm"><i class="fas fa-bars"></i></div>
        <div>
            <h2 class="fw-bold text-dark mb-1">Hifz Progress Tracker</h2>
            <p class="text-muted fw-semibold mb-0"><i class="fas fa-star me-2 text-warning"></i> Keep up the consistency, InshaAllah!</p>
        </div>
    </div>

    <div class="row g-4 mb-5 fade-up" style="animation-delay: 0.1s;">
        <div class="col-md-4">
            <div class="stat-box">
                <i class="fas fa-quran bg-icon"></i>
                <h6 class="text-white-50 fw-bold text-uppercase small">Memorization Goal</h6>
                <h2 class="fw-bold mb-0"><?= $stats['total_surahs'] ?> <span style="font-size: 16px;">Surahs Done</span></h2>
            </div>
        </div>
        <div class="col-md-8">
            <div class="tracker-card d-flex align-items-center" style="padding: 20px;">
                <div class="me-4"><i class="fas fa-award fa-3x text-warning"></i></div>
                <div>
                    <h6 class="fw-bold text-dark mb-1">Current Motivation</h6>
                    <p class="mb-0 text-muted small">"The best among you are those who learn the Quran and teach it." (Bukhari)</p>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 fade-up" style="animation-delay: 0.2s;">
        <div class="col-lg-5">
            <div class="tracker-card">
                <h5 class="fw-bold text-dark mb-4"><i class="fas fa-pen-nib me-2 text-success"></i> Log Today's Progress</h5>
                
                <?php if($success): ?> <div class="alert alert-success border-0 rounded-4 shadow-sm fw-bold small"><i class="fas fa-check-circle me-2"></i><?= $success ?></div> <?php endif; ?>
                <?php if($error): ?> <div class="alert alert-danger border-0 rounded-4 shadow-sm fw-bold small"><i class="fas fa-info-circle me-2"></i><?= $error ?></div> <?php endif; ?>

                <form method="POST">
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Activity Type</label>
                        <select name="lesson_type" class="form-select shadow-none" required>
                            <option value="Sabaq (New Lesson)">Sabaq (নতুন সবক)</option>
                            <option value="Sabaqi (Recent Rev.)">Sabaqi (সাতকড়ি)</option>
                            <option value="Manzil (Old Rev.)">Manzil (আমমোখতা)</option>
                        </select>
                    </div>
                    
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Surah or Juz Name</label>
                        <input type="text" name="surah_name" class="form-control shadow-none" placeholder="e.g. Surah Al-Kahf" required>
                    </div>

                    <div class="mb-5">
                        <label class="form-label fw-bold text-muted small text-uppercase">Ayah / Page Range</label>
                        <input type="text" name="ayah_range" class="form-control shadow-none" placeholder="e.g. Ayah 1-10 or Page 45" required>
                    </div>

                    <button type="submit" class="btn-submit shadow-lg">
                        SUBMIT TO TEACHER <i class="fas fa-paper-plane ms-2"></i>
                    </button>
                </form>
            </div>
        </div>

        <div class="col-lg-7">
            <div class="tracker-card">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="fw-bold text-dark mb-0"><i class="fas fa-history me-2 text-primary"></i> Activity Log</h5>
                    <span class="badge bg-light text-muted border px-3 py-2 rounded-pill">Recent 10 Entries</span>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead>
                            <tr class="small text-uppercase text-muted fw-bold">
                                <th class="border-0">Lesson</th>
                                <th class="border-0">Details</th>
                                <th class="border-0 text-end">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(!empty($hifz_logs)): foreach($hifz_logs as $log): ?>
                            <tr>
                                <td class="py-3">
                                    <div class="fw-bold text-dark" style="font-size: 14px;"><?= htmlspecialchars((string)$log['lesson_type']) ?></div>
                                    <small class="text-muted fw-bold"><i class="far fa-calendar-alt me-1"></i> <?= date('d M, Y', strtotime($log['log_date'])) ?></small>
                                </td>
                                <td class="py-3">
                                    <div class="fw-bold text-primary" style="font-size: 15px;"><?= htmlspecialchars((string)$log['surah_name']) ?></div>
                                    <small class="text-muted fw-bold">Ayah: <?= htmlspecialchars((string)$log['ayah_range']) ?></small>
                                </td>
                                <td class="text-end py-3">
                                    <?php 
                                        $b_class = 'bg-pending';
                                        if($log['status'] == 'Excellent') $b_class = 'bg-excellent';
                                        elseif($log['status'] == 'Needs Practice') $b_class = 'bg-practice';
                                    ?>
                                    <span class="status-badge <?= $b_class ?> shadow-sm"><?= htmlspecialchars((string)$log['status']) ?></span>
                                </td>
                            </tr>
                            <?php endforeach; else: ?>
                            <tr><td colspan="3" class="text-center py-5 text-muted fw-bold">No history found. Start logging!</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // Modern Sidebar Toggle Logic
    document.addEventListener("DOMContentLoaded", function() {
        const toggleBtn = document.getElementById('sidebarToggle');
        const sidebar = document.getElementById('sidebarMenu');
        if (toggleBtn && sidebar) {
            toggleBtn.addEventListener('click', () => sidebar.classList.toggle('active'));
        }
    });
</script>

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