<?php

namespace App\Http\Controllers;

use App\Models\Attendance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Barryvdh\DomPDF\Facade\Pdf;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class AttendanceController extends Controller
{
    public function index(Request $request)
    {
        $perPage = $request->get('per_page', 10);
        $perPage = in_array($perPage, [5, 10, 15, 20, 25, 50, 100]) ? $perPage : 10;

        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $search = $request->get('search', '');

        // Valid sort columns
        $validSortColumns = ['created_at', 'name', 'class', 'session', 'score'];
        if (!in_array($sortBy, $validSortColumns)) {
            $sortBy = 'created_at';
        }

        // Valid sort orders
        if (!in_array($sortOrder, ['asc', 'desc'])) {
            $sortOrder = 'desc';
        }

        $query = Attendance::query();

        // Apply search filter
        if (!empty($search)) {
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', '%' . $search . '%')
                  ->orWhere('class', 'like', '%' . $search . '%')
                  ->orWhere('session', 'like', '%' . $search . '%');
            });
        }

        // Apply class filter
        $classFilter = $request->get('class_filter', '');
        if (!empty($classFilter)) {
            $query->where('class', $classFilter);
        }

        $attendances = $query->orderBy($sortBy, $sortOrder)->paginate($perPage);
        return response()->json($attendances);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'class' => 'required|string',
            'session' => 'required|string',
            'file' => 'required|file|mimes:pdf,doc,docx,jpg,png,txt,xlsx,xls,rtf,log,js,php,py,java,cpp,html,css,sql,xml,json,md',
            'score' => 'nullable|numeric|min:0|max:100',
        ]);

        $filePath = null;
        if ($request->hasFile('file')) {
            $classFolder = str_replace(' ', '_', $request->input('class')); // Replace spaces with underscores for folder names
            $sessionFolder = str_replace(' ', '_', $request->input('session'));
            $name = str_replace(' ', '_', $request->input('name')); // Replace spaces with underscores for filename
            $extension = $request->file('file')->getClientOriginalExtension();
            $fileName = "{$name}_{$classFolder}_{$sessionFolder}.{$extension}";
            $filePath = $request->file('file')->storeAs("ujian/{$classFolder}/{$sessionFolder}", $fileName, 'public');
        }

        $attendance = Attendance::create([
            'name' => $request->input('name'),
            'class' => $request->input('class'),
            'session' => $request->input('session'),
            'file_path' => $filePath,
            'score' => $request->input('score'),
        ]);

        return response()->json($attendance, 201);
    }

    public function update(Request $request, Attendance $attendance)
    {
        $request->validate([
            'name' => 'required|string',
            'class' => 'required|string',
            'session' => 'required|string',
            'score' => 'nullable|numeric|min:0|max:100',
        ]);

        $attendance->update([
            'name' => $request->input('name'),
            'class' => $request->input('class'),
            'session' => $request->input('session'),
            'score' => $request->input('score'),
        ]);

        return response()->json($attendance);
    }

    public function updateScore(Request $request, $id)
    {
        // Debug: Log the request
        \Log::info('UpdateScore called', [
            'user_id' => auth()->id(),
            'user_role' => auth()->user()->role,
            'attendance_id' => $id,
            'score' => $request->input('score')
        ]);

        $request->validate([
            'score' => 'required|numeric|min:0|max:100',
        ]);

        $attendance = Attendance::findOrFail($id);

        // Check authorization manually
        if (!in_array(auth()->user()->role, ['admin', 'teacher'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $attendance->update(['score' => $request->input('score')]);

        return response()->json([
            'message' => 'Score updated successfully',
            'attendance' => $attendance
        ]);
    }

    public function destroy($id)
    {
        $attendance = Attendance::findOrFail($id);

        // Delete the file if it exists
        if ($attendance->file_path && Storage::disk('public')->exists($attendance->file_path)) {
            Storage::disk('public')->delete($attendance->file_path);
        }

        $attendance->delete();

        return response()->json(['message' => 'Attendance record deleted successfully']);
    }

    public function exportExcel(Request $request)
    {
        // Debug: Log that export was called
        \Log::info('Excel export called by user: ' . auth()->user()->name);

        // Get filtered data
        $query = Attendance::query();

        // Apply search filter
        $search = $request->get('search', '');
        if (!empty($search)) {
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', '%' . $search . '%')
                  ->orWhere('class', 'like', '%' . $search . '%')
                  ->orWhere('session', 'like', '%' . $search . '%');
            });
        }

        // Apply class filter
        $classFilter = $request->get('class_filter', '');
        if (!empty($classFilter)) {
            $query->where('class', $classFilter);
        }

        // Apply sorting
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $validSortColumns = ['created_at', 'name', 'class', 'session', 'score'];
        if (!in_array($sortBy, $validSortColumns)) {
            $sortBy = 'created_at';
        }
        if (!in_array($sortOrder, ['asc', 'desc'])) {
            $sortOrder = 'desc';
        }

        $attendances = $query->orderBy($sortBy, $sortOrder)->get();

        // Create Excel file using PhpSpreadsheet
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // Set headers
        $sheet->setCellValue('A1', 'Name');
        $sheet->setCellValue('B1', 'Class');
        $sheet->setCellValue('C1', 'Session');
        $sheet->setCellValue('D1', 'Score');
        $sheet->setCellValue('E1', 'Submission Date');
        $sheet->setCellValue('F1', 'Has File');

        // Style headers
        $headerStyle = [
            'font' => [
                'bold' => true,
                'color' => ['rgb' => 'FFFFFF'],
            ],
            'fill' => [
                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                'startColor' => ['rgb' => '34495E'],
            ],
        ];
        $sheet->getStyle('A1:F1')->applyFromArray($headerStyle);

        // Add data rows
        $row = 2;
        foreach ($attendances as $attendance) {
            $sheet->setCellValue('A' . $row, $attendance->name);
            $sheet->setCellValue('B' . $row, $attendance->class);
            $sheet->setCellValue('C' . $row, $attendance->session);
            $sheet->setCellValue('D' . $row, $attendance->score ?: 'Not graded');
            $sheet->setCellValue('E' . $row, $attendance->created_at->format('Y-m-d H:i:s'));
            $sheet->setCellValue('F' . $row, $attendance->file_path ? 'Yes' : 'No');
            $row++;
        }

        // Auto-size columns
        foreach (range('A', 'F') as $column) {
            $sheet->getColumnDimension($column)->setAutoSize(true);
        }

        // Create writer and save to temporary file
        $writer = new Xlsx($spreadsheet);
        $filename = 'attendance_records_' . date('Y-m-d_H-i-s') . '.xlsx';
        $tempFile = tempnam(sys_get_temp_dir(), 'excel');

        $writer->save($tempFile);

        return response()->download($tempFile, $filename, [
            'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        ])->deleteFileAfterSend(true);
    }

    public function exportPdf(Request $request)
    {
        // Debug: Log that export was called
        \Log::info('PDF export called by user: ' . auth()->user()->name);

        // Get filtered data
        $query = Attendance::query();

        // Apply search filter
        $search = $request->get('search', '');
        if (!empty($search)) {
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', '%' . $search . '%')
                  ->orWhere('class', 'like', '%' . $search . '%')
                  ->orWhere('session', 'like', '%' . $search . '%');
            });
        }

        // Apply class filter
        $classFilter = $request->get('class_filter', '');
        if (!empty($classFilter)) {
            $query->where('class', $classFilter);
        }

        // Apply sorting
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $validSortColumns = ['created_at', 'name', 'class', 'session', 'score'];
        if (!in_array($sortBy, $validSortColumns)) {
            $sortBy = 'created_at';
        }
        if (!in_array($sortOrder, ['asc', 'desc'])) {
            $sortOrder = 'desc';
        }

        $attendances = $query->orderBy($sortBy, $sortOrder)->get();

        // Create HTML content for PDF printing
        $filename = 'attendance_records_' . date('Y-m-d_H-i-s') . '.html';

        // Create HTML content optimized for PDF conversion
        $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Exam Attendance Records</title>
    <style>
        @page {
            margin: 1in;
            size: A4;
        }
        body {
            font-family: "DejaVu Sans", "Arial Unicode MS", Arial, sans-serif;
            font-size: 12px;
            line-height: 1.4;
            color: #333;
            margin: 0;
            padding: 0;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 2px solid #333;
            padding-bottom: 20px;
        }
        .header h1 {
            font-size: 24px;
            font-weight: bold;
            margin: 0 0 10px 0;
            color: #2c3e50;
        }
        .header .date {
            font-size: 11px;
            color: #666;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            font-size: 11px;
        }
        th {
            background-color: #34495e;
            color: white;
            padding: 10px 8px;
            text-align: left;
            font-weight: bold;
            border: 1px solid #ddd;
        }
        td {
            padding: 8px;
            border: 1px solid #ddd;
            vertical-align: top;
        }
        tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        tr:hover {
            background-color: #e8f4fd;
        }
        .footer {
            text-align: center;
            font-size: 10px;
            color: #666;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #ddd;
        }
        .summary {
            background-color: #ecf0f1;
            padding: 15px;
            margin: 20px 0;
            border-radius: 5px;
            border: 1px solid #bdc3c7;
        }
        .summary strong {
            color: #2c3e50;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>📚 Exam Attendance Records</h1>
        <div class="date">Generated on: ' . date('l, F j, Y \a\t g:i A') . '</div>
    </div>

    <div class="summary">
        <strong>Total Records:</strong> ' . $attendances->count() . ' |
        <strong>Generated by:</strong> ' . auth()->user()->name . ' |
        <strong>Filters Applied:</strong> ' . (!empty($classFilter) ? 'Class: ' . $classFilter : 'All Classes') . '
    </div>

    <table>
        <thead>
            <tr>
                <th style="width: 5%;">#</th>
                <th style="width: 25%;">Student Name</th>
                <th style="width: 15%;">Class</th>
                <th style="width: 15%;">Session</th>
                <th style="width: 10%;">Score</th>
                <th style="width: 15%;">Submission Date</th>
                <th style="width: 15%;">Attachment</th>
            </tr>
        </thead>
        <tbody>';

        $counter = 1;
        foreach ($attendances as $attendance) {
            $html .= '
            <tr>
                <td style="text-align: center; font-weight: bold;">' . $counter++ . '</td>
                <td>' . htmlspecialchars($attendance->name) . '</td>
                <td>' . htmlspecialchars($attendance->class) . '</td>
                <td>' . htmlspecialchars($attendance->session) . '</td>
                <td style="text-align: center;">' . ($attendance->score ? $attendance->score . '/100' : '<em>Not graded</em>') . '</td>
                <td>' . $attendance->created_at->format('M j, Y g:i A') . '</td>
                <td style="text-align: center;">' . ($attendance->file_path ? '✓ Yes' : '✗ No') . '</td>
            </tr>';
        }

        $html .= '
        </tbody>
    </table>

    <div class="footer">
        <p>This report was generated from the Exam Attendance Management System</p>
        <p>© ' . date('Y') . ' - All rights reserved</p>
    </div>
</body>
</html>';

        // Generate PDF using DomPDF
        $pdf = Pdf::loadHTML($html);
        $filename = 'attendance_records_' . date('Y-m-d_H-i-s') . '.pdf';

        return $pdf->download($filename);
    }
}