<?php

namespace App\Http\Controllers\Warehouse;

use App\Http\Controllers\Controller;
use App\Models\Warehouse\ProjectDivision;
use Illuminate\Http\Request;

class ProjectDivisionController extends Controller
{
    public function __construct()
    {
        $this->middleware('warehouse.access');
        $this->middleware('warehouse.permission:warehouse.project-divisions.view')->only(['index', 'show']);
        $this->middleware('warehouse.permission:warehouse.project-divisions.create')->only(['create', 'store']);
        $this->middleware('warehouse.permission:warehouse.project-divisions.edit')->only(['edit', 'update']);
        $this->middleware('warehouse.permission:warehouse.project-divisions.delete')->only(['destroy']);
    }

    /**
     * Display a listing of project divisions.
     */
    public function index(Request $request)
    {
        if ($request->expectsJson()) {
            return $this->getDataForTable($request);
        }

        return view('warehouse.project-divisions.index');
    }

    /**
     * Get data for DataTable.
     */
    private function getDataForTable(Request $request)
    {
        $start = $request->get('start', 0);
        $length = $request->get('length', 25);
        $search = $request->input('search.value');

        $query = ProjectDivision::query();

        // Apply search
        if (!empty($search)) {
            $query->search($search);
        }

        // Apply filters
        if ($request->filled('status')) {
            $query->where('status', $request->get('status'));
        }

        // Get total count
        $totalRecords = ProjectDivision::count();
        $filteredRecords = $query->count();

        // Apply pagination
        $divisions = $query->skip($start)
                          ->take($length)
                          ->orderBy('created_at', 'desc')
                          ->get();

        // Format data for DataTable
        $data = $divisions->map(function ($division) {
            return [
                'id' => $division->id,
                'division_name' => $division->division_name,
                'division_code' => $division->division_code,
                'description' => $division->description ?: '-',
                'status' => $division->status,
                'projects_count' => $division->projects()->count(),
                'created_at' => $division->created_at->format('M d, Y H:i'),
            ];
        });

        return response()->json([
            'draw' => intval($request->get('draw')),
            'recordsTotal' => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'data' => $data
        ]);
    }

    /**
     * Show the form for creating a new project division.
     */
    public function create()
    {
        return view('warehouse.project-divisions.create');
    }

    /**
     * Store a newly created project division.
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'division_name' => 'required|string|max:255',
            'division_code' => 'required|string|max:10|unique:project_divisions,division_code',
            'description' => 'nullable|string|max:1000',
            'status' => 'required|in:active,inactive',
        ]);

        try {
            $division = ProjectDivision::create($validatedData);

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'data' => $division,
                    'message' => 'Project division created successfully'
                ], 201);
            }

            return redirect()->route('warehouse.project-divisions.index')
                           ->with('success', 'Project division created successfully');

        } catch (\Exception $e) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => $e->getMessage()
                ], 400);
            }

            return back()->withErrors(['error' => $e->getMessage()])->withInput();
        }
    }

    /**
     * Display the specified project division.
     */
    public function show(Request $request, $id)
    {
        $division = ProjectDivision::with('projects')->findOrFail($id);

        if ($request->expectsJson()) {
            return response()->json($division);
        }

        return view('warehouse.project-divisions.show', compact('division'));
    }

    /**
     * Show the form for editing the specified project division.
     */
    public function edit($id)
    {
        $division = ProjectDivision::findOrFail($id);
        return view('warehouse.project-divisions.edit', compact('division'));
    }

    /**
     * Update the specified project division.
     */
    public function update(Request $request, $id)
    {
        $division = ProjectDivision::findOrFail($id);

        $validatedData = $request->validate([
            'division_name' => 'required|string|max:255',
            'division_code' => 'required|string|max:10|unique:project_divisions,division_code,' . $id,
            'description' => 'nullable|string|max:1000',
            'status' => 'required|in:active,inactive',
        ]);

        try {
            $division->update($validatedData);

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'data' => $division,
                    'message' => 'Project division updated successfully'
                ]);
            }

            return redirect()->route('warehouse.project-divisions.index')
                           ->with('success', 'Project division updated successfully');

        } catch (\Exception $e) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => $e->getMessage()
                ], 400);
            }

            return back()->withErrors(['error' => $e->getMessage()])->withInput();
        }
    }

    /**
     * Remove the specified project division.
     */
    public function destroy($id)
    {
        $division = ProjectDivision::findOrFail($id);

        // Check if division has projects
        if ($division->projects()->count() > 0) {
            return response()->json([
                'success' => false,
                'message' => 'Cannot delete division that has associated projects'
            ], 400);
        }

        try {
            $division->delete();

            return response()->json([
                'success' => true,
                'message' => 'Project division deleted successfully'
            ]);

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