<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');
require_once('source/restrict_user.php');

// Database connection (single connection)
$host = 'localhost';
$dbname = 'vdacocmz_schdb_coll';
$user = 'vdacocmz_mendohz';
$pass = '@Dei22*#';

try {
    $DBH = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => false
    ]);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Get admin info
$admin_name = "";
$rows = sql($DBH, "SELECT * FROM tbl_admin where status = ?", array("Active"), "rows");
foreach($rows as $row) {
    $admin_name = $row['username'];
}

// Handle query messages for UI
if(isset($_GET['msg'])) {
    if($_GET['msg'] == "refered") {
        $_SESSION['success_message'] = "Referred successfully";
    } else if($_GET['msg'] == "failed") {
        $_SESSION['error_message'] = "Something went wrong, please try again";
    }
}

/*
 * CSV import handler
 * Matches existing records by registration_no + year + term
 * If a matching record exists -> update it (and set csv_no to current import key)
 * Otherwise -> insert new record
 */
if(isset($_POST['importSubmit'])) {
    $teacher_no = strip_tags($_POST['teacher_no']);
    $s_term = strip_tags($_POST['term']);
    $s_year = strip_tags($_POST['year']);

    try {
        // Get teacher's class and subclass
        $stmt = $DBH->prepare("SELECT class, subclass FROM tbl_user WHERE hash = ?");
        $stmt->execute([$teacher_no]);
        $teacher_data = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($teacher_data) {
            $s_class = $teacher_data['class'];
            $s_subclass = $teacher_data['subclass'];
        } else {
            throw new Exception("Teacher not found");
        }

        // Unique import identifier for this upload (applied to all rows in this import)
        $key = mt_rand(100000, 999999);

        // Allowed CSV MIME types
        $csvMimes = array(
            'text/x-comma-separated-values','text/comma-separated-values',
            'application/octet-stream','application/vnd.ms-excel',
            'application/x-csv','text/x-csv','text/csv',
            'application/csv','application/excel','application/vnd.msexcel',
            'text/plain'
        );

        if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvMimes)) {
            if(is_uploaded_file($_FILES['file']['tmp_name'])) {
                $csvFile = fopen($_FILES['file']['tmp_name'], 'r');

                // Read header row (if present)
                $header = fgetcsv($csvFile);

                $success_count = 0;
                $error_count = 0;
                $error_details = [];
                $row_index = 1; // header is row 1

                while(($line = fgetcsv($csvFile)) !== FALSE) {
                    $row_index++;
                    try {
                        // Ensure sufficient columns (your expected format: 7 columns)
                        if(count($line) < 7) {
                            $error_details[] = "Row {$row_index}: Insufficient columns (expected 7, found " . count($line) . ")";
                            $error_count++;
                            continue;
                        }

                        // Map CSV columns
                        $name = trim($line[0]);
                        $registration_no = trim($line[1]);
                        $present = trim($line[2]);
                        $sch_open = trim($line[3]);
                        $date_of_report = trim($line[4]);
                        $next_term_begins = trim($line[5]);
                        $teachers_remarks = trim($line[6]);

                        // Minimal validation
                        if(empty($name) || empty($registration_no)) {
                            $error_details[] = "Row {$row_index}: Missing name or registration number";
                            $error_count++;
                            continue;
                        }

                        // Normalize dates (if present) to YYYY-MM-DD or keep as-is if empty
                        if(!empty($date_of_report)) {
                            $d = date_create($date_of_report);
                            if($d) $date_of_report = $d->format('Y-m-d');
                        }
                        if(!empty($next_term_begins)) {
                            $d2 = date_create($next_term_begins);
                            if($d2) $next_term_begins = $d2->format('Y-m-d');
                        }

                        // Check if a record exists for this student in same year & term
                        $check_stmt = $DBH->prepare("SELECT id FROM attendance WHERE registration_no = ? AND year = ? AND term = ? LIMIT 1");
                        $check_stmt->execute([$registration_no, $s_year, $s_term]);
                        $existing = $check_stmt->fetch(PDO::FETCH_ASSOC);

                        if ($existing && isset($existing['id'])) {
                            // Update existing record (also update csv_no to current import key)
                            $update_stmt = $DBH->prepare("
                                UPDATE attendance SET
                                    name = ?, Present = ?, SchOpen = ?, DateOfReport = ?, NextTermBegins = ?, TeachersRemarks = ?,
                                    class = ?, subclass = ?, year = ?, teacher_no = ?, term = ?, csv_no = ?
                                WHERE id = ?
                            ");
                            $update_stmt->execute([
                                $name, $present, $sch_open, $date_of_report, $next_term_begins, $teachers_remarks,
                                $s_class, $s_subclass, $s_year, $teacher_no, $s_term, $key,
                                $existing['id']
                            ]);
                        } else {
                            // Insert new record
                            $insert_stmt = $DBH->prepare("
                                INSERT INTO attendance
                                    (name, registration_no, Present, SchOpen, DateOfReport, NextTermBegins, TeachersRemarks,
                                     class, subclass, year, teacher_no, csv_no, term)
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                            ");
                            $insert_stmt->execute([
                                $name, $registration_no, $present, $sch_open, $date_of_report, $next_term_begins, $teachers_remarks,
                                $s_class, $s_subclass, $s_year, $teacher_no, $key, $s_term
                            ]);
                        }

                        $success_count++;
                    } catch(PDOException $e) {
                        $error_details[] = "Row {$row_index}: Database error - " . $e->getMessage();
                        $error_count++;
                    }
                }

                fclose($csvFile);

                // Prepare session messages and redirect query string
                if($success_count > 0) {
                    $_SESSION['success_message'] = "Successfully processed {$success_count} attendance records";

                    if($error_count > 0) {
                        $_SESSION['warning_message'] = "{$error_count} records had errors";
                        $_SESSION['error_details'] = $error_details;
                    }

                    // Store key in session for reference
                    $_SESSION['last_csv_no'] = $key;

                    $qstring = "?status=success&val=" . $key . "&records=" . $success_count;
                } else {
                    $_SESSION['error_message'] = "No records were imported. Please check your CSV file format.";
                    $_SESSION['error_details'] = $error_details;
                    $qstring = "?status=error&type=no_records";
                }
            } else {
                $_SESSION['error_message'] = "File upload failed";
                $qstring = "?status=error&type=upload_failed";
            }
        } else {
            $_SESSION['error_message'] = "Invalid file type. Please upload a CSV file.";
            $qstring = "?status=error&type=invalid_file";
        }
    } catch(Exception $e) {
        $_SESSION['error_message'] = "Error: " . $e->getMessage();
        $qstring = "?status=error&type=exception";
    }

    header("Location: post_attendance.php" . $qstring);
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>VERBUM DEI INT'L COLLEGE - Upload Attendance</title>
  <link rel="icon" type="image/png" href="https://portal.vda.com.ng/coll_admin/coll_logo.jpg">

  <!-- Bootstrap 5 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

  <!-- Custom CSS -->
  <style>
    :root {
      --primary-color: #1976d2;
      --secondary-color: #64b5f6;
      --accent-color: #bbdefb;
      --dark-color: #0d47a1;
      --light-color: #e3f2fd;
    }
    body {
      font-family: 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      background-color: var(--light-color);
      padding-top: 56px;
    }
    .sidebar {
      background: linear-gradient(180deg, var(--dark-color) 0%, var(--primary-color) 100%);
      position: fixed;
      top: 56px;
      left: -250px;
      width: 250px;
      height: calc(100vh - 56px);
      transition: all 0.3s;
      z-index: 1000;
      overflow-y: auto;
    }
    .sidebar.active { left: 0; }
    .sidebar .nav-link { color: rgba(255,255,255,0.85); font-weight:600; padding:.75rem 1rem; margin-bottom:.2rem; transition: all .2s; }
    .sidebar .nav-link:hover { color:#fff; background-color: rgba(255,255,255,0.15); }
    .sidebar .nav-link.active { color:#fff; background-color: var(--secondary-color); box-shadow:0 2px 5px rgba(0,0,0,.1); }
    .main-content { margin-left:0; width:100%; transition: all .3s; min-height: calc(100vh - 56px); }
    @media (min-width:992px) { .sidebar { left:0 } .main-content { margin-left:250px; width:calc(100% - 250px); } body { padding-top:0; } }
    .navbar { background-color: var(--primary-color); box-shadow: 0 0.15rem 1.75rem 0 rgba(33,37,41,0.1); position: fixed; top:0; width:100%; z-index:1030; color:white; }
    .card { border:none; border-radius:.5rem; box-shadow: 0 0.15rem 1.75rem 0 rgba(58,59,69,0.1); margin-bottom:1.5rem; transition: transform .2s, box-shadow .2s; }
    .card:hover { transform: translateY(-2px); box-shadow:0 0.5rem 1.5rem rgba(0,0,0,.1); }
    .card-header { background-color: var(--accent-color); border-bottom: 1px solid var(--secondary-color); font-weight:700; color: var(--dark-color); }
    .admin-info { display:flex; align-items:center; background-color: rgba(255,255,255,0.2); padding:8px 12px; border-radius:.5rem; color:white; }
    #importFrm { display: none; animation: slideDown .3s ease; }
    @keyframes slideDown { from { opacity:0; transform: translateY(-10px); } to { opacity:1; transform: translateY(0); } }
    .uploaded-year { background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)); color:white; padding:15px; border-radius:8px; text-align:center; transition: all .3s ease; text-decoration:none; display:block; }
  </style>
</head>

<body>
  <!-- Top Navigation -->
  <nav class="navbar navbar-expand-lg navbar-dark">
    <div class="container-fluid">
      <button id="sidebarToggle" class="btn btn-link d-lg-none me-2">
        <i class="fas fa-bars"></i>
      </button>
      <a class="navbar-brand d-none d-lg-block" href="#">
        VERBUM DEI INT'L COLLEGE
      </a>
      <div class="ms-auto d-flex align-items-center">
        <div class="admin-info me-3">
          <span class="admin-name"><?php echo htmlspecialchars($admin_name); ?></span>
          <span class="admin-access">(Administrator)</span>
          <i class="fas fa-user-circle admin-icon"></i>
        </div>
        <a href="logout.php" class="btn btn-sm btn-outline-light">
          <i class="fas fa-sign-out-alt"></i>
        </a>
      </div>
    </div>
  </nav>

  <!-- Sidebar -->
  <nav id="sidebar" class="sidebar">
    <div class="position-sticky pt-3">
      <div class="text-center mb-4 d-none d-lg-block">
        <img src="https://portal.vda.com.ng/coll_admin/coll_logo.jpg" alt="School Logo" class="rounded-circle" width="80">
        <h5 class="mt-2 text-white">VERBUM DEI INT'L COLLEGE</h5>
        <p class="text-white-50 small">Admin Dashboard</p>
      </div>

      <ul class="nav flex-column">
        <li class="nav-item"><a class="nav-link" href="main.php"><i class="fas fa-fw fa-tachometer-alt"></i> Admin Centre</a></li>
        <li class="nav-item"><a class="nav-link active" href="post_attendance.php"><i class="fas fa-fw fa-calendar-check"></i> Upload Attendance</a></li>
        <li class="nav-item"><a class="nav-link" href="post_skills.php"><i class="fas fa-fw fa-chart-bar"></i> Upload Skills</a></li>
      </ul>
    </div>
  </nav>

  <!-- Main Content -->
  <main class="main-content">
    <div class="container-fluid px-4 pt-4">
      <!-- Page Heading -->
      <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Upload Student's Attendance</h1>
        <div class="d-none d-sm-inline-block">
          <span class="badge bg-light text-dark p-2">
            <i class="fas fa-phone-alt me-1"></i> Support: MENDOH - 08032929756
          </span>
        </div>
      </div>

      <!-- Messages -->
      <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
          <?php echo $_SESSION['success_message']; ?>
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['success_message']); ?>
      <?php endif; ?>

      <?php if (isset($_SESSION['warning_message'])): ?>
        <div class="alert alert-warning alert-dismissible fade show" role="alert">
          <?php echo $_SESSION['warning_message']; ?>
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['warning_message']); ?>
      <?php endif; ?>

      <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
          <?php echo $_SESSION['error_message']; ?>
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['error_message']); ?>
      <?php endif; ?>

      <!-- Upload Form Card -->
      <div class="row">
        <div class="col-lg-12">
          <div class="card shadow mb-4">
            <div class="card-header py-3">
              <h6 class="m-0 font-weight-bold text-primary">
                Upload Student's Attendance, Closing Date, Resumption Date, Teacher's Comment, etc.
                <button type="button" onclick="$('#importFrm');" class="btn btn-sm btn-outline-primary float-begin" style="color:green">
                  <i class="fas fa-upload me-1" style="color:purple"></i> Click Here to Import Data for Attendace, Comment, etc
                </button>
              </h6>
            </div>
            <div class="card-body">
              <!-- Import Form -->
              <form action="post_attendance.php" method="post" enctype="multipart/form-data" id="importFrm">
                <div class="mb-3">
                  <label for="file" class="form-label">Choose CSV File</label>
                  <input type="file" name="file" class="form-control" id="file" accept=".csv" required>
                  <div class="form-text">Upload a CSV file with student attendance data</div>
                </div>

                <div class="row g-3">
                  <div class="col-md-3">
                    <label for="term" class="form-label">Term</label>
                    <select name="term" class="form-select" id="term" required>
                      <option value="1st Term">1st Term</option>
                      <option value="2nd Term">2nd Term</option>
                      <option value="3rd Term">3rd Term</option>
                    </select>
                  </div>

                  <div class="col-md-3">
                    <label for="year" class="form-label">Academic Year</label>
                    <select name="year" class="form-select" id="year" required>
                      <?php
                      $rows1 = sql($DBH, "SELECT * FROM tbl_session where id >= ?", array(1), "rows");
                      foreach($rows1 as $row1) {
                        $sch_session = $row1['session'];
                        echo "<option value='".htmlspecialchars($sch_session)."'>".htmlspecialchars($sch_session)."</option>";
                      }
                      ?>
                    </select>
                  </div>

                  <div class="col-md-4">
                    <label for="teacher_no" class="form-label">Class Teacher</label>
                    <select name="teacher_no" class="form-select" id="teacher_no" required>
                      <?php
                      $rows1 = sql($DBH, "SELECT * FROM tbl_user where teacher = ?", array("true"), "rows");
                      foreach($rows1 as $row1) {
                        $sch_hash = $row1['hash'];
                        $sch_name = $row1['fullname'];
                        $sc_class = $row1['class'];
                        echo "<option value='".htmlspecialchars($sch_hash)."'>".htmlspecialchars($sc_class . " - " . $sch_name)."</option>";
                      }
                      ?>
                    </select>
                  </div>

                  <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100" name="importSubmit">
                      <i class="fas fa-upload me-1"></i> UPLOAD
                    </button>
                  </div>
                </div>
              </form>

              <div class="mt-4">
                <a href="https://rportal.lahs.com.ng/admin/SAMPLE_ATTENDANCE_SHEET.csv" class="btn btn-outline-danger" target="_blank">
                  <i class="fas fa-download me-1"></i> Download Sample CSV Format
                </a>
              </div>

              <div class="mt-4">
                <h6 class="text-primary"><i class="fas fa-info-circle me-2"></i>What You Can Upload:</h6>
                <div class="row">
                  <div class="col-md-6">
                    <ul class="list-group list-group-flush">
                      <li class="list-group-item"><i class="fas fa-check text-success me-2"></i> Student Attendance Records</li>
                      <li class="list-group-item"><i class="fas fa-check text-success me-2"></i> School Closing Dates</li>
                      <li class="list-group-item"><i class="fas fa-check text-success me-2"></i> School Resumption Dates</li>
                    </ul>
                  </div>
                  <div class="col-md-6">
                    <ul class="list-group list-group-flush">
                      <li class="list-group-item"><i class="fas fa-check text-success me-2"></i> Next Term Information</li>
                      <li class="list-group-item"><i class="fas fa-check text-success me-2"></i> Teacher's Comments</li>
                      <li class="list-group-item"><i class="fas fa-check text-success me-2"></i> Report Generation Date</li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Uploaded Attendance Section -->
      <div class="card shadow mb-4">
        <div class="card-header py-3" style="background-color: var(--accent-color);">
          <h6 class="m-0 font-weight-bold text-primary">
            <i class="fas fa-history me-2"></i>Previously Uploaded Attendance Records
          </h6>
        </div>
        <div class="card-body" style="background-color: var(--light-color);">
          <div class="row">
            <?php
            $STH = $DBH->prepare("SELECT count(*) FROM attendance WHERE id >= ?");
            $STH->execute(array(1));
            $count = $STH->fetchColumn();

            if($count >= 1) {
              $rows = sql($DBH, "SELECT MIN(id) AS id, year FROM attendance WHERE id >= ? GROUP BY year", array(1), "rows");
              foreach($rows as $row) {
                $t_year = $row['year'];
                echo '
                <div class="col-md-3 mb-3">
                  <a href="main_term.php?id='.htmlspecialchars($t_year).'" target="_blank" class="uploaded-year">
                    <i class="fas fa-calendar-alt fa-2x mb-2"></i><br>
                    <strong>'.htmlspecialchars($t_year).'</strong><br>
                    <small>Click to view details</small>
                  </a>
                </div>';
              }
            } else {
              echo '<div class="col-12 text-center py-5">
                <i class="fas fa-calendar-times fa-3x mb-3 text-muted"></i>
                <h5 class="text-muted">No Attendance Records Found</h5>
                <p class="text-muted">Upload your first attendance record using the form above.</p>
              </div>';
            }
            ?>
          </div>
        </div>
      </div>
    </div>
  </main>

  <!-- Footer -->
  <footer class="footer">
    <div class="container-fluid">
      <div class="row align-items-center">
        <div class="col-md-6">
          <span class="copyright-text">Copyright &copy; VERBUM DEI INT'L COLLEGE <?php echo date("Y"); ?></span>
        </div>
        <div class="col-md-6">
          <div class="powered-by">
            <a href="https://dataswift.com.ng" target="_blank" rel="noopener noreferrer" class="powered-by-link">
              <span>Powered by DataSwift</span>
              <img src="datalogo.png" alt="DataSwift Logo">
            </a>
          </div>
        </div>
      </div>
    </div>
  </footer>

  <!-- Bootstrap 5 JS Bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

  <!-- JavaScript -->
  <script>
  // Toggle sidebar on mobile
  document.getElementById('sidebarToggle').addEventListener('click', function() {
    document.getElementById('sidebar').classList.toggle('active');
    document.querySelector('.main-content').classList.toggle('active');
  });

  // Toggle import form with animation
  $(document).ready(function() {
    // Show/hide import form
    $('button[onclick*="importFrm"]').click(function() {
      $('#importFrm').slideToggle();
    });

    // File input styling
    $('#file').change(function() {
      var fileName = $(this).val().split('\\').pop();
      if(fileName) {
        $(this).next('.form-text').html('Selected: <strong>' + fileName + '</strong>');
      }
    });
  });
  </script>
</body>
</html>
