<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\WoffPattern;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class WoffPatternController extends Controller
{
    // ✅ LIST WITH PAGINATION + SEARCH
    public function index(Request $request)
    {
        try {
            $query = WoffPattern::query();

            if (!empty($request->search)) {
                $search = $request->search;

                $query->where(function ($q) use ($search) {
                    $q->where('WOP_name', 'LIKE', "%$search%")
                      ->orWhere('WOP_code', 'LIKE', "%$search%")
                      ->orWhere('description', 'LIKE', "%$search%");
                });
            }

            $perPage = $request->get('per_page', 10);
            $data = $query->paginate($perPage);

            return response()->json([
                'success' => true,
                'data' => $data,
                'message' => 'Woff Pattern list fetched successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error fetching data',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    // ✅ ALL DATA (with formatted pattern)
    public function all()
    {
        $patterns = WoffPattern::all();

        $formattedPatterns = $patterns->map(function ($pattern) {
            return $pattern->getFormattedPattern();
        });

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

    // ✅ STORE (with pattern_data)
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'WOP_name' => 'nullable|string|max:100',
            'WOP_code' => 'nullable|string|max:50',
            'description' => 'nullable|string',
            'pattern_data' => 'nullable|array',           // ✅ NEW
            'pattern_data.days' => 'nullable|array|size:42', // ✅ Must have 42 days
            'Is_Active' => 'nullable|boolean'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        $data = $request->all();
        $data['Is_Active'] = $data['Is_Active'] ?? 1;

        // ✅ Ensure pattern_data has days array
        if (!isset($data['pattern_data']) || !is_array($data['pattern_data'])) {
            $data['pattern_data'] = ['days' => array_fill(0, 42, 0)];
        }

        $record = WoffPattern::create($data);

        return response()->json([
            'success' => true,
            'data' => $record->getFormattedPattern(),
            'message' => 'Created successfully'
        ]);
    }

   // ✅ SHOW (with all fields like index/all)
public function show($id)
{
    try {
        $pattern = WoffPattern::findOrFail($id);

        // Format the pattern similar to index/all function
        $formattedData = [
            'WOP_id' => $pattern->WOP_id,
            'WOP_code' => $pattern->WOP_code,
            'WOP_name' => $pattern->WOP_name,
            'description' => $pattern->description,
            'pattern_data' => $pattern->pattern_data,  // Raw JSON
            'pattern_days' => $pattern->getPatternDaysAttribute(),  // 42 days array
            'weeks' => [
                'week1' => array_slice($pattern->getPatternDaysAttribute(), 0, 7),
                'week2' => array_slice($pattern->getPatternDaysAttribute(), 7, 7),
                'week3' => array_slice($pattern->getPatternDaysAttribute(), 14, 7),
                'week4' => array_slice($pattern->getPatternDaysAttribute(), 21, 7),
                'week5' => array_slice($pattern->getPatternDaysAttribute(), 28, 7),
                'week6' => array_slice($pattern->getPatternDaysAttribute(), 35, 7)
            ],
            'Is_Active' => $pattern->Is_Active,
            'created_at' => $pattern->created_at,
            'updated_at' => $pattern->updated_at,
            'deleted_at' => $pattern->deleted_at
        ];

        return response()->json([
            'success' => true,
            'data' => $formattedData,
            'message' => 'Pattern retrieved successfully'
        ]);

    } catch (ModelNotFoundException $e) {
        return response()->json([
            'success' => false,
            'message' => 'Record not found'
        ], 404);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error fetching pattern',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
        ], 500);
    }
}

    // ✅ UPDATE (with pattern_data)
    public function update(Request $request, $id)
    {
        try {
            $record = WoffPattern::findOrFail($id);

            $validator = Validator::make($request->all(), [
                'WOP_name' => 'nullable|string|max:100',
                'WOP_code' => 'nullable|string|max:50',
                'description' => 'nullable|string',
                'pattern_data' => 'nullable|array',
                'pattern_data.days' => 'nullable|array|size:42',
                'Is_Active' => 'nullable|boolean'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }

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

            return response()->json([
                'success' => true,
                'data' => $record->getFormattedPattern(),
                'message' => 'Updated successfully'
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Record not found'
            ], 404);
        }
    }

    // ✅ DELETE (Soft Delete)
    public function destroy($id)
    {
        try {
            $record = WoffPattern::findOrFail($id);
            $record->delete();

            return response()->json([
                'success' => true,
                'message' => 'Deleted successfully'
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Record not found'
            ], 404);
        }
    }

    // ✅ ADDITIONAL: Get week-off dates for an employee (requires mapping table)
    public function getEmployeeWeekOff($empId, Request $request)
    {
        $year = $request->get('year', date('Y'));
        $month = $request->get('month', date('m'));

        // This requires employee_week_off_mapping table
        // You'll need to create that separately

        return response()->json([
            'success' => true,
            'message' => 'This endpoint requires employee_week_off_mapping table'
        ]);
    }
}
