<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Attendance;
use App\Models\Employee;
use Carbon\Carbon;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;

class AttendanceController extends Controller
{
    public function getDailyAttendance(Request $request)
    {
        $request->validate(['date' => 'required|date']);

        try {
            $date = $request->date;
            $employeesQuery = Employee::with(['position', 'branch'])->where('is_active', true);
            
            if ($request->has('branch_id') && !empty($request->branch_id)) {
                $employeesQuery->where('branch_id', $request->branch_id);
            }
            
            $employees = $employeesQuery->orderBy('name', 'asc')->get();
            $attendances = Attendance::where('date', $date)->get()->keyBy('employee_id');

            $data = $employees->map(function($emp) use ($attendances, $date) {
                $att = $attendances->get($emp->id);
                return [
                    'employee_id'   => $emp->id,
                    'employee_code' => $emp->employee_code,
                    'employee_name' => $emp->name,
                    'position'      => $emp->position->name ?? '-',
                    'branch'        => $emp->branch->name ?? '-',
                    'status'        => $att ? $att->status : 'hadir',
                    'check_in'      => $att ? $att->check_in : '08:00',
                    'check_out'     => $att ? $att->check_out : '17:00',
                    'notes'         => $att ? $att->notes : ''
                ];
            });

            return response()->json(['success' => true, 'data' => $data]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function getSummary(Request $request)
    {
        $request->validate([
            'start_date' => 'required|date',
            'end_date'   => 'required|date|after_or_equal:start_date',
        ]);

        try {
            $employeesQuery = Employee::with(['position', 'branch'])->where('is_active', true);
            
            if ($request->has('branch_id') && !empty($request->branch_id)) {
                $employeesQuery->where('branch_id', $request->branch_id);
            }
            
            $employees = $employeesQuery->orderBy('name', 'asc')->get();
            $attendances = Attendance::whereBetween('date', [$request->start_date, $request->end_date])->get();

            $data = $employees->map(function($emp) use ($attendances) {
                $empAtt = $attendances->where('employee_id', $emp->id);
                return [
                    'employee_id'   => $emp->id,
                    'employee_code' => $emp->employee_code,
                    'employee_name' => $emp->name,
                    'position'      => $emp->position->name ?? '-',
                    'branch'        => $emp->branch->name ?? '-',
                    'hadir'         => $empAtt->where('status', 'hadir')->count(),
                    'sakit'         => $empAtt->where('status', 'sakit')->count(),
                    'izin'          => $empAtt->where('status', 'izin')->count(),
                    'cuti'          => $empAtt->where('status', 'cuti')->count(),
                    'alpha'         => $empAtt->where('status', 'alpha')->count(),
                    'total_input'   => $empAtt->count()
                ];
            });

            return response()->json(['success' => true, 'data' => $data]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function storeBulk(Request $request)
    {
        $request->validate([
            'date' => 'required|date',
            'attendances' => 'required|array',
            'attendances.*.employee_id' => 'required|exists:employees,id',
            'attendances.*.status' => 'required|in:hadir,sakit,izin,alpha,cuti'
        ]);

        DB::beginTransaction();
        try {
            $date = $request->date;
            $userId = $request->user()->id ?? 1;

            foreach ($request->attendances as $row) {
                Attendance::updateOrCreate(
                    [
                        'employee_id' => $row['employee_id'],
                        'date'        => $date
                    ],
                    [
                        'status'     => $row['status'],
                        'check_in'   => in_array($row['status'], ['hadir']) ? ($row['check_in'] ?? null) : null,
                        'check_out'  => in_array($row['status'], ['hadir']) ? ($row['check_out'] ?? null) : null,
                        'notes'      => $row['notes'] ?? null,
                        'created_by' => $userId
                    ]
                );
            }

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Data absensi berhasil disimpan.']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * GENERATE TEMPLATE EXCEL (.XLSX)
     */
    public function downloadTemplate(Request $request)
    {
        $date = $request->date ?? date('Y-m-d');
        
        $query = Employee::with('branch')->where('is_active', true);
        if ($request->has('branch_id') && !empty($request->branch_id)) {
            $query->where('branch_id', $request->branch_id);
        }
        $employees = $query->orderBy('name', 'asc')->get();

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        
        // Setup Header
        $headers = ['Tanggal_YYYY-MM-DD', 'NIK', 'Nama_Karyawan', 'Cabang', 'Status', 'Jam_Masuk', 'Jam_Pulang', 'Keterangan'];
        $columnLetter = 'A';
        foreach ($headers as $header) {
            $sheet->setCellValue($columnLetter . '1', $header);
            $sheet->getColumnDimension($columnLetter)->setAutoSize(true);
            $columnLetter++;
        }
        $sheet->getStyle('A1:H1')->getFont()->setBold(true);
        $sheet->getStyle('A1:H1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('E2E8F0');

        $row = 2;
        foreach ($employees as $emp) {
            $sheet->setCellValue('A' . $row, $date);
            $sheet->setCellValue('B' . $row, $emp->employee_code);
            $sheet->setCellValue('C' . $row, $emp->name);
            $sheet->setCellValue('D' . $row, $emp->branch->name ?? '-');
            $sheet->setCellValue('E' . $row, 'hadir');
            $sheet->setCellValue('F' . $row, '08:00');
            $sheet->setCellValue('G' . $row, '17:00');
            $sheet->setCellValue('H' . $row, '');
            $row++;
        }

        $writer = new Xlsx($spreadsheet);
        $filename = "Template_Absensi_" . $date . ".xlsx";
        
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        
        $writer->save('php://output');
        exit;
    }

    /**
     * UPLOAD & BACA FILE EXCEL (.XLSX)
     */
    public function importExcel(Request $request)
    {
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls'
        ]);

        $file = $request->file('file');
        
        DB::beginTransaction();
        try {
            $spreadsheet = IOFactory::load($file->getPathname());
            $worksheet = $spreadsheet->getActiveSheet();
            $rows = $worksheet->toArray();
            
            $userId = $request->user()->id ?? 1;
            $count = 0;

            foreach ($rows as $index => $data) {
                if ($index === 0) continue; // Lewati baris pertama (Header)
                if (empty($data[0]) || empty($data[1])) continue; // Lewati jika tanggal atau NIK kosong

                // Antisipasi format tanggal dari Excel (Serial Number 44xxx atau String YYYY-MM-DD)
                $dateRaw = $data[0];
                if (is_numeric($dateRaw)) {
                    $date = Date::excelToDateTimeObject($dateRaw)->format('Y-m-d');
                } else {
                    $date = date('Y-m-d', strtotime(trim($dateRaw)));
                }

                $nik      = trim($data[1]);
                $status   = strtolower(trim($data[4] ?? 'hadir'));
                $checkIn  = trim($data[5] ?? null);
                $checkOut = trim($data[6] ?? null);
                $notes    = trim($data[7] ?? null);

                $employee = Employee::where('employee_code', $nik)->first();
                
                if ($employee) {
                    Attendance::updateOrCreate(
                        [
                            'employee_id' => $employee->id,
                            'date'        => $date
                        ],
                        [
                            'status'     => in_array($status, ['hadir', 'sakit', 'izin', 'alpha', 'cuti']) ? $status : 'hadir',
                            'check_in'   => $status === 'hadir' ? $checkIn : null,
                            'check_out'  => $status === 'hadir' ? $checkOut : null,
                            'notes'      => $notes,
                            'created_by' => $userId
                        ]
                    );
                    $count++;
                }
            }
            
            DB::commit();
            return response()->json(['success' => true, 'message' => "$count Data absensi berhasil diimpor dari Excel."]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => 'Gagal membaca file. Pastikan Anda menggunakan file Excel berformat .xlsx yang valid.'], 500);
        }
    }
}