<?php
require_once __DIR__ . '/_auth.php';

/* --------------------------------------------------------
   PROCESS FORM BEFORE LAYOUT LOAD
-------------------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $title        = trim($_POST['title'] ?? '');
    $desc         = trim($_POST['description'] ?? '');
    $course_id    = (int)($_POST['course_id'] ?? 0);
    $batch_id_in  = trim($_POST['batch_id'] ?? '');
    $visible_from = $_POST['visible_from'] ?: date('Y-m-d H:i:s');
    $visible_to   = $_POST['visible_to'] ?? 'ALL'; // New field (ALL, COURSE, BATCH, STUDENT)
    $admin_id     = $_SESSION['admin_id'] ?? 1;

    // Normalize batch
    $batch_id = 0;
    if ($batch_id_in !== '' && ctype_digit($batch_id_in)) $batch_id = (int)$batch_id_in;

    // Validate
    if ($title && $course_id) {
        $filePaths = [];

        // MULTI FILE UPLOAD HANDLER
        if (!empty($_FILES['media']['name']) && is_array($_FILES['media']['name'])) {
            $folder = __DIR__ . '/../uploads/classes/';
            if (!is_dir($folder)) mkdir($folder, 0777, true);

            foreach ($_FILES['media']['name'] as $i => $fname) {
                if ($_FILES['media']['error'][$i] === 0) {
                    $newName = time() . '_' . preg_replace('/[^A-Za-z0-9_.-]/', '_', $fname);
                    if (move_uploaded_file($_FILES['media']['tmp_name'][$i], $folder . $newName)) {
                        $filePaths[] = 'uploads/classes/' . $newName;
                    }
                }
            }
        }

        // Insert main record
        $ctype = count($filePaths) ? 'mixed' : 'text';

        $sql = "INSERT INTO daily_classes
                (course_id, batch_id, title, description, content_type, visible_from, visible_to, created_by, is_active)
                VALUES (?, NULLIF(?,0), ?, ?, ?, ?, ?, ?, 1)";
        $st = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($st, "iissssii", 
            $course_id, $batch_id, $title, $desc, $ctype, $visible_from, $visible_to, $admin_id
        );

        if (!mysqli_stmt_execute($st)) {
            die("Error saving record: " . mysqli_stmt_error($st));
        }
        $class_id = mysqli_insert_id($conn);
        mysqli_stmt_close($st);

        // Insert media files
        if (!empty($filePaths)) {
            $stm = mysqli_prepare($conn, "INSERT INTO daily_class_media(class_id,file_path) VALUES (?,?)");
            foreach ($filePaths as $fp) {
                mysqli_stmt_bind_param($stm, "is", $class_id, $fp);
                mysqli_stmt_execute($stm);
            }
            mysqli_stmt_close($stm);
        }

        header("Location: class_content.php?msg=" . urlencode("Class uploaded successfully."));
        exit;
    } else {
        header("Location: class_content.php?msg=" . urlencode("Please fill all required fields."));
        exit;
    }
}

/* --------------------------------------------------------
   LAYOUT + DATA
-------------------------------------------------------- */
require_once __DIR__ . '/_layout.php';
admin_header('Class Uploads');

// Dropdown data
$courses = mysqli_query($conn, "SELECT id,name FROM courses WHERE is_active=1 ORDER BY name");
$batches = mysqli_query($conn, "
    SELECT b.id,b.name,c.name AS course_name
    FROM batches b JOIN courses c ON c.id=b.course_id
    ORDER BY c.name,b.name
");

$msg = $_GET['msg'] ?? '';
?>

<h2 style="color:#2563eb;margin:0 0 10px">📚 Class Content Manager</h2>
<?php if ($msg): ?>
<div class="card mt-2" style="background:#dcfce7;border-color:#86efac;color:#166534;font-weight:500">
  <?= htmlspecialchars($msg) ?>
</div>
<?php endif; ?>

<div class="grid mt-3" style="gap:20px">
  <!-- Upload Section -->
  <div class="col-5 card" style="border-top:4px solid #2563eb">
    <h3 style="margin:0 0 12px;color:#1e40af;">➕ Add New Class</h3>

    <form method="post" enctype="multipart/form-data" style="display:grid;gap:12px">
      <input type="hidden" name="action" value="add">

      <label>Course</label>
      <select name="course_id" required>
        <option value="">Select Course</option>
        <?php while($c = mysqli_fetch_assoc($courses)): ?>
          <option value="<?=$c['id']?>"><?=htmlspecialchars($c['name'])?></option>
        <?php endwhile; ?>
      </select>

      <label>Batch (Optional)</label>
      <select name="batch_id">
        <option value="">All Batches</option>
        <?php while($b = mysqli_fetch_assoc($batches)): ?>
          <option value="<?=$b['id']?>"><?=htmlspecialchars($b['course_name'].' - '.$b['name'])?></option>
        <?php endwhile; ?>
      </select>

      <label>Visibility</label>
      <select name="visible_to" required>
        <option value="ALL">All Students</option>
        <option value="COURSE">By Course</option>
        <option value="BATCH">By Batch</option>
        <option value="STUDENT">Specific Student</option>
      </select>

      <label>Title</label>
      <input name="title" placeholder="e.g. HTML Layout Basics" required>

      <label>Description</label>
      <textarea name="description" placeholder="Lesson summary, notes, etc."></textarea>

      <label>Visible From</label>
      <input type="datetime-local" name="visible_from" value="<?=date('Y-m-d\TH:i')?>">

      <label>Upload Files (images, video, PDFs)</label>
      <input type="file" name="media[]" multiple>

      <button class="btn primary mt-2" style="width:max-content;background:#2563eb">Upload Class</button>
    </form>
  </div>

  <!-- Listing Section -->
  <div class="col-7 card" style="border-top:4px solid #16a34a">
    <h3 style="margin:0 0 12px;color:#166534;">🗓️ Recent Classes</h3>

    <div style="overflow:auto;max-height:600px;border-radius:10px;border:1px solid var(--border)">
      <table style="min-width:860px">
        <thead>
          <tr>
            <th>Date</th>
            <th>Course</th>
            <th>Batch</th>
            <th>Visible To</th>
            <th>Title</th>
            <th>Files</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php
          $rows = mysqli_query($conn, "
            SELECT d.*, c.name AS course, b.name AS batch
            FROM daily_classes d
            LEFT JOIN courses c ON c.id=d.course_id
            LEFT JOIN batches b ON b.id=d.batch_id
            ORDER BY d.created_at DESC LIMIT 20
          ");
          if (mysqli_num_rows($rows) == 0): ?>
            <tr><td colspan="7" style="text-align:center;padding:24px;color:#64748b">No classes yet.</td></tr>
          <?php endif; ?>

          <?php while($r = mysqli_fetch_assoc($rows)):
            $med = mysqli_query($conn, "SELECT file_path FROM daily_class_media WHERE class_id={$r['id']}");
            $mcount = mysqli_num_rows($med);
          ?>
            <tr>
              <td><?=date('d M, H:i', strtotime($r['created_at']))?></td>
              <td><?=htmlspecialchars($r['course'])?></td>
              <td><?=htmlspecialchars($r['batch'] ?: '-')?></td>
              <td><?=htmlspecialchars($r['visible_to'])?></td>
              <td style="font-weight:600"><?=htmlspecialchars($r['title'])?></td>
              <td style="text-align:center"><?=$mcount?></td>
              <td>
                <form method="post" action="delete_class.php" onsubmit="return confirm('Delete this class?')" style="display:inline">
                  <input type="hidden" name="id" value="<?=$r['id']?>">
                  <button class="btn" style="padding:5px 8px;color:#991b1b;border-color:#fecaca">Delete</button>
                </form>
              </td>
            </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php admin_footer(); ?>
