<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Models\User;
use App\Services\ExcelExportService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class ExportController extends Controller
{
    public function attendanceExport(Request $request)
    {
        $request->validate([
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date',
            'user_id' => 'nullable|exists:users,id',
        ]);

        $user = Auth::user();
        $company = $user->company;

        if (!$company) {
            return response()->json([
                'success' => false,
                'message' => 'User tidak memiliki perusahaan',
            ], 400);
        }

        // Build query - hide super_admin from export (using Spatie roles)
        // Include activities for URAIAN and OUTPUT columns
        // Include location (unified), office (legacy), businessTripLocation (legacy) for KETERANGAN column
        $query = Attendance::with(['user', 'company', 'activities', 'location', 'office', 'businessTripLocation'])
            ->where('company_id', $company->id)
            ->whereHas('user', function ($q) {
                $q->whereDoesntHave('roles', function ($r) {
                    $r->where('name', 'super_admin');
                });
            });

        // Date filters
        $startDate = $request->start_date ? Carbon::parse($request->start_date) : null;
        $endDate = $request->end_date ? Carbon::parse($request->end_date) : null;

        if ($startDate) {
            $query->where('date', '>=', $startDate);
        }
        if ($endDate) {
            $query->where('date', '<=', $endDate);
        }

        // User filter
        $filterUser = null;
        if ($request->user_id) {
            $query->where('user_id', $request->user_id);
            $filterUser = User::find($request->user_id);
        }

        // Order by date and user
        $query->orderBy('date', 'desc')
            ->orderBy('user_id');

        $attendances = $query->get();

        if ($attendances->isEmpty()) {
            return response()->json([
                'success' => false,
                'message' => 'Tidak ada data kehadiran untuk periode yang dipilih',
            ], 404);
        }

        // Generate export
        $exportService = new ExcelExportService();
        $filePath = $exportService->exportAttendance(
            $attendances,
            $company,
            $startDate,
            $endDate,
            $filterUser
        );

        // Generate download URL
        $downloadUrl = route('api.export.download', ['path' => $filePath]);

        return response()->json([
            'success' => true,
            'message' => 'Export berhasil dibuat',
            'data' => [
                'file_path' => $filePath,
                'download_url' => $downloadUrl,
                'filename' => basename($filePath),
                'total_records' => $attendances->count(),
            ],
        ]);
    }

    public function download(Request $request)
    {
        $path = $request->query('path');

        if (!$path) {
            return response()->json([
                'success' => false,
                'message' => 'Path tidak valid',
            ], 400);
        }

        // ExcelExportService saves to storage_path('app/' . $path)
        // So we need to use the same path here
        $fullPath = storage_path('app/' . $path);

        if (!file_exists($fullPath)) {
            return response()->json([
                'success' => false,
                'message' => 'File tidak ditemukan',
            ], 404);
        }

        $filename = basename($path);
        $mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

        return response()->download($fullPath, $filename, [
            'Content-Type' => $mimeType,
        ]);
    }

    public function myAttendanceExport(Request $request)
    {
        $request->validate([
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date',
            'month' => 'nullable|integer|min:1|max:12',
            'year' => 'nullable|integer|min:2020',
        ]);

        $user = Auth::user();
        $company = $user->company;

        if (!$company) {
            return response()->json([
                'success' => false,
                'message' => 'User tidak memiliki perusahaan',
            ], 400);
        }

        // Build query for current user only
        // Include activities for URAIAN and OUTPUT columns
        // Include location (unified), office (legacy), businessTripLocation (legacy) for KETERANGAN column
        $query = Attendance::with(['user', 'company', 'activities', 'location', 'office', 'businessTripLocation'])
            ->where('user_id', $user->id);

        // Date filters
        $startDate = null;
        $endDate = null;

        if ($request->month && $request->year) {
            // Filter by month/year
            $startDate = Carbon::create($request->year, $request->month, 1)->startOfMonth();
            $endDate = Carbon::create($request->year, $request->month, 1)->endOfMonth();
        } else {
            // Use start_date and end_date
            $startDate = $request->start_date ? Carbon::parse($request->start_date) : null;
            $endDate = $request->end_date ? Carbon::parse($request->end_date) : null;
        }

        if ($startDate) {
            $query->where('date', '>=', $startDate);
        }
        if ($endDate) {
            $query->where('date', '<=', $endDate);
        }

        // Order by date
        $query->orderBy('date', 'desc');

        $attendances = $query->get();

        if ($attendances->isEmpty()) {
            return response()->json([
                'success' => false,
                'message' => 'Tidak ada data kehadiran untuk periode yang dipilih',
            ], 404);
        }

        // Generate export
        $exportService = new ExcelExportService();
        $filePath = $exportService->exportAttendance(
            $attendances,
            $company,
            $startDate,
            $endDate,
            $user
        );

        // Generate download URL
        $downloadUrl = route('api.export.download', ['path' => $filePath]);

        return response()->json([
            'success' => true,
            'message' => 'Export berhasil dibuat',
            'data' => [
                'file_path' => $filePath,
                'download_url' => $downloadUrl,
                'filename' => basename($filePath),
                'total_records' => $attendances->count(),
            ],
        ]);
    }
}
