<?php

namespace App\Http\Controllers;

use App\Models\YaumiyahActivity;
use App\Models\YaumiyahRecord;
use App\Models\Anggota;
use App\Exports\YaumiyahRecordExport;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class YaumiyahController extends Controller
{
    /**
     * Display a listing of activities.
     */
    public function index(Request $request)
    {
        // Get filter parameters
        $anggotaId = $request->get('anggota_id');
        $week = $request->get('week');
        $year = $request->get('year', now()->year);
        $activityId = $request->get('activity_id');

        // Get all activities
        $activities = YaumiyahActivity::where('is_active', true)
            ->orderBy('sort_order')
            ->get();

        // Get all anggota for filter dropdown
        $anggota = Anggota::all();

        // Get records with filters
        $query = YaumiyahRecord::with(['anggota', 'activity']);

        if ($anggotaId) {
            $query->where('anggota_id', $anggotaId);
        }

        if ($week) {
            $query->where('week_number', $week);
        }

        if ($year) {
            $query->where('year', $year);
        }

        if ($activityId) {
            $query->where('yaumiyah_activity_id', $activityId);
        }

        $records = $query->orderBy('year', 'desc')
            ->orderBy('week_number', 'desc')
            ->orderBy('anggota_id')
            ->paginate(20);

        // Get statistics
        $totalRecords = YaumiyahRecord::count();
        $weekRecords = YaumiyahRecord::where('week_number', now()->weekOfYear)
            ->where('year', now()->year)
            ->count();
        $yearRecords = YaumiyahRecord::where('year', now()->year)->count();

        return view('yaumiyah.index', compact(
            'activities',
            'anggota',
            'records',
            'totalRecords',
            'weekRecords',
            'yearRecords',
            'anggotaId',
            'week',
            'year',
            'activityId'
        ));
    }

    /**
     * Export records to Excel
     */
    public function export(Request $request)
    {
        $filters = [
            'anggota_id' => $request->get('anggota_id'),
            'week' => $request->get('week'),
            'year' => $request->get('year'),
        ];

        return Excel::download(new YaumiyahRecordExport($filters), 'data-yaumiyah.xlsx');
    }

    /**
     * Show the form for creating a new activity.
     */
    public function create()
    {
        return view('yaumiyah.activities.create');
    }

    /**
     * Store a newly created activity.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'target_per_week' => 'required|integer|min:0',
            'unit' => 'required|string|max:50',
            'sort_order' => 'required|integer|min:0'
        ]);

        YaumiyahActivity::create($request->all());

        return redirect()->route('yaumiyah.activities.index')
            ->with('success', 'Aktivitas berhasil ditambahkan.');
    }

    /**
     * Display the specified activity.
     */
    public function show(YaumiyahActivity $activity)
    {
        return view('yaumiyah.activities.show', compact('activity'));
    }

    /**
     * Show the form for editing the specified activity.
     */
    public function edit(YaumiyahActivity $activity)
    {
        return view('yaumiyah.activities.edit', compact('activity'));
    }

    /**
     * Update the specified activity.
     */
    public function update(Request $request, YaumiyahActivity $activity)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'target_per_week' => 'required|integer|min:0',
            'unit' => 'required|string|max:50',
            'sort_order' => 'required|integer|min:0'
        ]);

        $activity->update($request->all());

        return redirect()->route('yaumiyah.activities.index')
            ->with('success', 'Aktivitas berhasil diperbarui.');
    }

    /**
     * Remove the specified activity.
     */
    public function destroy(YaumiyahActivity $activity)
    {
        $activity->delete();

        return redirect()->route('yaumiyah.activities.index')
            ->with('success', 'Aktivitas berhasil dihapus.');
    }

    /**
     * Show activities management page.
     */
    public function activities()
    {
        $activities = YaumiyahActivity::orderBy('sort_order')->get();
        return view('yaumiyah.activities.index', compact('activities'));
    }

    /**
     * Show records input page.
     */
    public function records(Request $request)
    {
        $week = $request->get('week', now()->weekOfYear);
        $year = $request->get('year', now()->year);
        $anggotaId = $request->get('anggota_id');

        $activities = YaumiyahActivity::where('is_active', true)
            ->orderBy('sort_order')
            ->get();

        $anggota = Anggota::all();

        // Get existing records for the selected week/year/anggota
        $existingRecords = [];
        if ($anggotaId) {
            $existingRecords = YaumiyahRecord::where('anggota_id', $anggotaId)
                ->where('week_number', $week)
                ->where('year', $year)
                ->get()
                ->keyBy('yaumiyah_activity_id');
        }

        return view('yaumiyah.records.index', compact(
            'activities', 
            'anggota', 
            'week', 
            'year', 
            'anggotaId', 
            'existingRecords'
        ));
    }

    /**
     * Store records for a specific week.
     */
    public function storeRecords(Request $request)
    {
        $request->validate([
            'anggota_id' => 'required|exists:tbl_anggota,id',
            'week_number' => 'required|integer|min:1|max:53',
            'year' => 'required|integer|min:2020|max:2030',
            'records' => 'required|array',
            'records.*.yaumiyah_activity_id' => 'required|exists:yaumiyah_activities,id',
            'records.*.value' => 'required|integer|min:0'
        ]);

        DB::transaction(function () use ($request) {
            $anggotaId = $request->anggota_id;
            $weekNumber = $request->week_number;
            $year = $request->year;

            // Delete existing records for this week/year/anggota
            YaumiyahRecord::where('anggota_id', $anggotaId)
                ->where('week_number', $weekNumber)
                ->where('year', $year)
                ->delete();

            // Insert new records
            foreach ($request->records as $record) {
                if ($record['value'] > 0) {
                    YaumiyahRecord::create([
                        'yaumiyah_activity_id' => $record['yaumiyah_activity_id'],
                        'anggota_id' => $anggotaId,
                        'week_number' => $weekNumber,
                        'year' => $year,
                        'value' => $record['value'],
                        'notes' => $record['notes'] ?? null,
                        'created_by' => 'admin',
                        'created_by_name' => auth()->user()->name ?? 'Admin'
                    ]);
                }
            }
        });

        return redirect()->route('yaumiyah.records', [
            'week' => $request->week_number,
            'year' => $request->year,
            'anggota_id' => $request->anggota_id
        ])->with('success', 'Data Yaumiyah berhasil disimpan.');
    }

    /**
     * Show list of all records.
     */
    public function recordsList(Request $request)
    {
        $anggotaId = $request->get('anggota_id');
        $week = $request->get('week');
        $year = $request->get('year', now()->year);

        $anggota = Anggota::all();

        // Get records with grouping
        $query = YaumiyahRecord::with(['anggota', 'activity'])
            ->select('anggota_id', 'week_number', 'year', 'created_by', 'created_by_name', 'created_at')
            ->selectRaw('COUNT(DISTINCT yaumiyah_activity_id) as total_activities')
            ->groupBy('anggota_id', 'week_number', 'year', 'created_by', 'created_by_name', 'created_at');

        if ($anggotaId) {
            $query->where('anggota_id', $anggotaId);
        }

        if ($week) {
            $query->where('week_number', $week);
        }

        if ($year) {
            $query->where('year', $year);
        }

        $records = $query->orderBy('year', 'desc')
            ->orderBy('week_number', 'desc')
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return view('yaumiyah.records.list', compact(
            'records',
            'anggota',
            'anggotaId',
            'week',
            'year'
        ));
    }

    /**
     * Show detail of a specific record.
     */
    public function recordsDetail(Request $request)
    {
        $anggotaId = $request->get('anggota_id');
        $week = $request->get('week');
        $year = $request->get('year');

        $anggota = Anggota::findOrFail($anggotaId);
        
        $activities = YaumiyahActivity::where('is_active', true)
            ->orderBy('sort_order')
            ->get();

        $records = YaumiyahRecord::where('anggota_id', $anggotaId)
            ->where('week_number', $week)
            ->where('year', $year)
            ->get()
            ->keyBy('yaumiyah_activity_id');

        return view('yaumiyah.records.detail', compact(
            'anggota',
            'activities',
            'records',
            'week',
            'year'
        ));
    }

    /**
     * Show reports for Yaumiyah.
     */
    public function reports(Request $request)
    {
        $year = $request->get('year', now()->year);
        $anggotaId = $request->get('anggota_id');

        $anggota = Anggota::all();
        $activities = YaumiyahActivity::where('is_active', true)
            ->orderBy('sort_order')
            ->get();

        $reports = collect();
        if ($anggotaId) {
            $reports = YaumiyahRecord::with(['activity', 'anggota'])
                ->where('anggota_id', $anggotaId)
                ->where('year', $year)
                ->get()
                ->groupBy(['anggota_id', 'week_number']);
        }

        return view('yaumiyah.reports', compact(
            'activities', 
            'anggota', 
            'year', 
            'anggotaId', 
            'reports'
        ));
    }

    /**
     * API method for member portal to get activities
     */
    public function apiActivities()
    {
        $activities = YaumiyahActivity::where('is_active', true)
            ->orderBy('sort_order')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $activities
        ]);
    }

    /**
     * API method for member portal to get records for specific member
     */
    public function apiRecords(Request $request)
    {
        $request->validate([
            'anggota_id' => 'required|exists:tbl_anggota,id',
            'week_number' => 'required|integer|min:1|max:53',
            'year' => 'required|integer|min:2020|max:2030'
        ]);

        $records = YaumiyahRecord::with('activity')
            ->where('anggota_id', $request->anggota_id)
            ->where('week_number', $request->week_number)
            ->where('year', $request->year)
            ->get()
            ->keyBy('yaumiyah_activity_id');

        return response()->json([
            'success' => true,
            'data' => $records
        ]);
    }

    /**
     * API method for member portal to store records
     */
    public function apiStoreRecords(Request $request)
    {
        $request->validate([
            'anggota_id' => 'required|exists:tbl_anggota,id',
            'week_number' => 'required|integer|min:1|max:53',
            'year' => 'required|integer|min:2020|max:2030',
            'records' => 'required|array',
            'records.*.yaumiyah_activity_id' => 'required|exists:yaumiyah_activities,id',
            'records.*.value' => 'required|integer|min:0',
            'member_name' => 'required|string|max:255'
        ]);

        DB::transaction(function () use ($request) {
            $anggotaId = $request->anggota_id;
            $weekNumber = $request->week_number;
            $year = $request->year;

            // Delete existing records for this week/year/anggota
            YaumiyahRecord::where('anggota_id', $anggotaId)
                ->where('week_number', $weekNumber)
                ->where('year', $year)
                ->delete();

            // Insert new records
            foreach ($request->records as $record) {
                if ($record['value'] > 0) {
                    YaumiyahRecord::create([
                        'yaumiyah_activity_id' => $record['yaumiyah_activity_id'],
                        'anggota_id' => $anggotaId,
                        'week_number' => $weekNumber,
                        'year' => $year,
                        'value' => $record['value'],
                        'notes' => $record['notes'] ?? null,
                        'created_by' => 'member',
                        'created_by_name' => $request->member_name
                    ]);
                }
            }
        });

        return response()->json([
            'success' => true,
            'message' => 'Data Yaumiyah berhasil disimpan.'
        ]);
    }
}
