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

// Admin Security Check
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['admin_logged_in'])) { header("Location: login.php"); exit; }

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

// ==========================================
// 🛠️ DATABASE AUTO-PATCHER
// ==========================================
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `teacher_feedback` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `student_id` int(11) NOT NULL,
        `teacher_name` varchar(100) NOT NULL,
        `subject` varchar(100) NOT NULL,
        `comment` text NOT NULL,
        `rating` int(1) DEFAULT 5,
        `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
} catch(PDOException $e) {}

// Handle Redirect Messages
if(isset($_GET['msg'])) {
    if($_GET['msg'] == 'added') $success_msg = "MashaAllah! Feedback published to student report.";
    elseif($_GET['msg'] == 'deleted') $success_msg = "Feedback removed successfully.";
    elseif($_GET['msg'] == 'error') $error_msg = "Something went wrong! Please try again.";
}

// ==========================================
// ⚙️ HANDLE FEEDBACK SUBMISSION
// ==========================================
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit_feedback'])) {
    $student_id = (int)$_POST['student_id'];
    $teacher = trim($_POST['teacher_name']);
    $subject = trim($_POST['subject']);
    $comment = trim($_POST['comment']);
    $rating = (int)$_POST['rating'];

    if (!empty($teacher) && !empty($comment)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO teacher_feedback (student_id, teacher_name, subject, comment, rating) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$student_id, $teacher, $subject, $comment, $rating]);
            echo "<script>window.location.href='?msg=added';</script>"; exit;
        } catch (Exception $e) { echo "<script>window.location.href='?msg=error';</script>"; exit; }
    } else { $error_msg = "Please fill in all required fields."; }
}

// DELETE LOGIC
if (isset($_GET['delete_id'])) {
    try {
        $pdo->prepare("DELETE FROM teacher_feedback WHERE id = ?")->execute([$_GET['delete_id']]);
        echo "<script>window.location.href='?msg=deleted';</script>"; exit;
    } catch (Exception $e) { echo "<script>window.location.href='?msg=error';</script>"; exit; }
}

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

// Data Fetching
$students = $pdo->query("SELECT id, name FROM students ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
$feedbacks = $pdo->query("SELECT f.*, s.name as student_name FROM teacher_feedback f JOIN students s ON f.student_id = s.id ORDER BY f.id DESC LIMIT 20")->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 Toggle */
    .premium-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; }

    /* Layout Cards */
    .glass-card { background: #fff; border-radius: 20px; border: 1px solid #e2e8f0; box-shadow: 0 10px 40px rgba(0,0,0,0.03); padding: 30px; }
    .recent-card { background: #fff; border-radius: 20px; border: 1px solid #e2e8f0; box-shadow: 0 10px 40px rgba(0,0,0,0.03); overflow: hidden; border-top: 5px solid var(--theme-gold); }
    
    /* Form Elements */
    .form-label { color: var(--theme-dark); font-size: 12px; text-transform: uppercase; letter-spacing: 1px; font-weight: 800; margin-bottom: 8px; }
    .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); }
    
    .btn-publish { background: var(--theme-green); color: white; border: none; padding: 15px; border-radius: 12px; font-weight: 800; width: 100%; transition: 0.3s; box-shadow: 0 8px 20px rgba(6,78,59,0.15); display: flex; align-items: center; justify-content: center; gap: 10px; }
    .btn-publish:hover { background: var(--theme-dark); transform: translateY(-2px); color: var(--theme-gold); }

    /* Desktop Table */
    .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; border-bottom: 1px solid #f1f5f9; }
    
    .rating-star { color: var(--theme-gold); font-size: 12px; }
    .act-del { width: 34px; height: 34px; display: inline-flex; align-items: center; justify-content: center; border-radius: 10px; background: #fef2f2; color: #ef4444; transition: 0.3s; text-decoration: none; }
    .act-del: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); } }

    /* 📱 Mobile Specific Styles (Card View) */
    .feedback-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; margin-bottom: 15px; }
    
    @media (max-width: 991.98px) {
        .main-content { padding: 15px !important; }
        .premium-header { padding: 20px; flex-direction: column; align-items: flex-start !important; gap: 15px; }
        .premium-header .d-flex { width: 100%; display: flex; justify-content: flex-start; align-items: center; gap: 15px; }
        #sidebarToggle { display: inline-flex !important; }
        .header-title { font-size: 1.2rem; }
    }
</style>

<div class="main-content p-3 p-md-4">
    
    <div class="premium-header d-flex justify-content-between align-items-center fade-up">
        <div class="d-flex align-items-center">
            <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-comment-dots me-2 text-success"></i> Mentorship & Feedback</h4>
                <p class="text-muted small fw-bold mb-0 d-none d-md-block">Record personalized remarks for student progress reports</p>
            </div>
        </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="row g-4">
        <div class="col-lg-5">
            <div class="glass-card fade-up" style="animation-delay: 0.1s;">
                <h5 class="fw-bold text-dark mb-4 pb-2 border-bottom"><i class="fas fa-pen-fancy me-2 text-success"></i> New Entry</h5>
                <form method="POST">
                    <div class="mb-4">
                        <label class="form-label">Target Student</label>
                        <div class="input-group">
                            <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-user-graduate"></i></span>
                            <select name="student_id" class="form-select border-start-0 ps-0 fw-bold text-dark" required>
                                <option value="">-- Choose Student --</option>
                                <?php foreach($students as $s): ?>
                                    <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label class="form-label">Teacher Name</label>
                            <input type="text" name="teacher_name" class="form-control fw-bold" placeholder="Teacher Name" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Subject</label>
                            <input type="text" name="subject" class="form-control fw-bold" placeholder="e.g. Quran" required>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label">Performance Grade</label>
                        <select name="rating" class="form-select fw-bold">
                            <option value="5">⭐⭐⭐⭐⭐ Excellent</option>
                            <option value="4">⭐⭐⭐⭐ Good</option>
                            <option value="3">⭐⭐⭐ Average</option>
                            <option value="2">⭐⭐ Needs Focus</option>
                            <option value="1">⭐ Poor</option>
                        </select>
                    </div>

                    <div class="mb-4">
                        <label class="form-label">Remarks / Instruction</label>
                        <textarea name="comment" class="form-control fw-medium" rows="4" placeholder="Write encouraging remarks for the student..." required></textarea>
                    </div>

                    <button type="submit" name="submit_feedback" class="btn-publish">
                        PUBLISH TO REPORT <i class="fas fa-paper-plane"></i>
                    </button>
                </form>
            </div>
        </div>

        <div class="col-lg-7">
            <div class="recent-card fade-up" style="animation-delay: 0.2s;">
                <div class="p-4 bg-light border-bottom d-flex justify-content-between align-items-center">
                    <h5 class="fw-bold text-dark mb-0"><i class="fas fa-history me-2 text-primary"></i> Recently Published</h5>
                    <span class="badge bg-white text-dark border shadow-sm px-3">Latest 20</span>
                </div>
                
                <div class="table-responsive d-none d-lg-block">
                    <table class="table table-hover align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Student</th>
                                <th>Feedback Summary</th>
                                <th class="text-end">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(!empty($feedbacks)): foreach($feedbacks as $f): ?>
                            <tr>
                                <td>
                                    <div class="fw-bold text-dark" style="font-size: 14px;"><?= htmlspecialchars($f['student_name']) ?></div>
                                    <small class="badge bg-light text-primary border mt-1" style="font-size: 10px;"><?= htmlspecialchars($f['subject']) ?></small>
                                </td>
                                <td>
                                    <div class="rating-star mb-1">
                                        <?php for($i=0; $i<$f['rating']; $i++) echo '<i class="fas fa-star"></i>'; ?>
                                    </div>
                                    <p class="mb-0 text-muted small" style="max-width: 300px; line-height: 1.4;">"<?= htmlspecialchars($f['comment']) ?>"</p>
                                    <small class="text-muted fw-bold" style="font-size: 10px;"><?= date('d M, Y', strtotime($f['created_at'])) ?></small>
                                </td>
                                <td class="text-end pe-4">
                                    <a href="?delete_id=<?= $f['id'] ?>" class="act-del shadow-sm" onclick="return confirm('Delete this feedback entry?')">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; else: ?>
                                <tr><td colspan="3" class="text-center py-5 text-muted fw-bold">No feedback posted yet.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <div class="p-3 d-block d-lg-none">
                    <?php if(!empty($feedbacks)): foreach($feedbacks as $f): ?>
                    <div class="feedback-mobile-card p-3">
                        <div class="d-flex justify-content-between align-items-start mb-3 border-bottom pb-2">
                            <div>
                                <h6 class="fw-bold text-dark mb-1"><?= htmlspecialchars($f['student_name']) ?></h6>
                                <span class="badge bg-light text-primary border" style="font-size: 9px;"><?= htmlspecialchars($f['subject']) ?></span>
                            </div>
                            <a href="?delete_id=<?= $f['id'] ?>" class="text-danger p-2" onclick="return confirm('Delete this feedback?')"><i class="fas fa-trash-alt"></i></a>
                        </div>
                        <div class="rating-star mb-2">
                            <?php for($i=0; $i<$f['rating']; $i++) echo '<i class="fas fa-star"></i>'; ?>
                        </div>
                        <p class="text-muted small mb-2 fw-medium" style="line-height: 1.5; font-style: italic;">"<?= htmlspecialchars($f['comment']) ?>"</p>
                        <div class="text-end border-top pt-2">
                            <small class="text-muted fw-bold" style="font-size: 10px;"><i class="far fa-clock me-1"></i><?= date('d M, Y', strtotime($f['created_at'])) ?></small>
                        </div>
                    </div>
                    <?php endforeach; else: ?>
                        <div class="text-center py-5 opacity-50"><i class="fas fa-comment-slash fa-3x mb-3"></i><p class="fw-bold">No logs found</p></div>
                    <?php endif; ?>
                </div>
            </div>
        </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'); }
            });
        }
    });
</script>

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