<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\User\Line;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class LineController extends Controller
{
    protected function userIdFromSession(Request $request)
    {
        return $request->session()->get('user_id');
    }

    public function create(Request $request)
    {
        $userId = $this->userIdFromSession($request);

        // Active
        $customers = Line::where('user_id', $userId)
            ->where('type', 'Customer')
            ->latest('line_id')
            ->get();

        $suppliers = Line::where('user_id', $userId)
            ->where('type', 'Supplier')
            ->latest('line_id')
            ->get();

        // Deleted (trashed)
        $customersDeleted = Line::onlyTrashed()
            ->where('user_id', $userId)
            ->where('type', 'Customer')
            ->latest('deleted_at')
            ->get();

        $suppliersDeleted = Line::onlyTrashed()
            ->where('user_id', $userId)
            ->where('type', 'Supplier')
            ->latest('deleted_at')
            ->get();

        return view('user.lines.create', compact(
            'customers',
            'suppliers',
            'customersDeleted',
            'suppliersDeleted'
        ));
    }

//     public function store(Request $request)
//     {
//         $userId = $this->userIdFromSession($request);
//         if (!$userId) {
//             return $request->ajax()
//                 ? response()->json(['status' => 'error', 'message' => 'Not authenticated'], 401)
//                 : redirect()->route('login')->with('error', 'Please log in first.');
//         }

//         $data = $request->validate([
//             'line_name' => ['required', 'string', 'max:255'],
//             'type' => ['required', Rule::in(['Customer', 'Supplier'])],
//         ]);

//         $lineName = trim($data['line_name']);
//         $type = $data['type'];

//         // Check if exists (active)
//         $exists = Line::where('user_id', $userId)
//             ->where('type', $type)
//             ->where('line_name', $lineName)
//             ->first();
// if ($exists !== null) {

            
//             return $request->ajax()
//                 ? response()->json(['status' => 'error', 'message' => 'Line already exists'], 422)
//                 : redirect()->back()->withErrors(['line_name' => 'Line already exists'])->withInput();
//         }

//         // Check if soft-deleted exists
//         $trashed = Line::withTrashed()
//             ->where('user_id', $userId)
//             ->where('type', $type)
//             ->where('line_name', $lineName)
//             ->whereNotNull('deleted_at')
//             ->first();

//         if ($trashed) {
//             $trashed->restore();
//             $trashed->update(['line_name' => $lineName]);

//             return $request->ajax()
//                 ? response()->json(['status' => 'ok', 'message' => 'Line restored successfully', 'line' => $trashed])
//                 : redirect()->route('user.lines.create')->with('success', 'Line restored successfully');
//         }

//         $line = Line::create([
//             'line_name' => $lineName,
//             'type' => $type,
//             'user_id' => $userId,
//         ]);

//         return $request->ajax()
//             ? response()->json(['status' => 'ok', 'message' => 'Line created successfully', 'line' => $line])
//             : redirect()->route('user.lines.create')->with('success', 'Line created successfully');
//     }

public function store(Request $request)
{
    $userId = $this->userIdFromSession($request);

    if (!$userId) {
        return $request->expectsJson()
            ? response()->json(['status' => 'error', 'message' => 'Not authenticated'], 401)
            : redirect()->route('login')->with('error', 'Please log in first.');
    }

    $data = $request->validate([
        'line_name' => ['required', 'string', 'max:255'],
        'type' => ['required', Rule::in(['Customer', 'Supplier'])],
    ]);

    $lineName = trim($data['line_name']);
    $type = $data['type'];

    // Check if exists (active)
    $exists = Line::where('user_id', $userId)
        ->where('type', $type)
        ->where('line_name', $lineName)
        ->first();

    if ($exists) {
        return response()->json([
            'status' => 'error',
            'message' => 'Line already exists'
        ], 422);
    }

    // Check soft deleted
    $trashed = Line::withTrashed()
        ->where('user_id', $userId)
        ->where('type', $type)
        ->where('line_name', $lineName)
        ->first();

    if ($trashed && $trashed->deleted_at) {
        $trashed->restore();
        return response()->json([
            'status' => 'ok',
            'message' => 'Line restored successfully',
            'line' => $trashed
        ]);
    }

    // Create new
    $line = Line::create([
        'line_name' => $lineName,
        'type' => $type,
        'user_id' => $userId,
    ]);

    return response()->json([
        'status' => 'ok',
        'message' => 'Line created successfully',
        'line' => $line
    ]);
}

    // public function update(Request $request, Line $line)
    // {
    //     $userId = $this->userIdFromSession($request);

    //     if ($line->user_id != $userId) {
    //         return $request->ajax()
    //             ? response()->json(['status' => 'error', 'message' => 'Unauthorized'], 403)
    //             : abort(403);
    //     }

    //     $data = $request->validate([
    //         'line_name' => [
    //             'required',
    //             'string',
    //             'max:255',
    //             Rule::unique('lines', 'line_name')
    //                 ->where(fn($q) => $q->where('user_id', $userId)->where('type', $line->type))
    //                 ->ignore($line->line_id, 'line_id'),
    //         ],
    //     ]);

    //     $line->update(['line_name' => trim($data['line_name'])]);

    //     return $request->ajax()
    //         ? response()->json(['status' => 'ok', 'message' => 'Line updated successfully', 'line' => $line])
    //         : redirect()->route('user.lines.create')->with('success', 'Line updated successfully');
    // }

    // public function destroy(Request $request, Line $line)
    // {
    //     $userId = $this->userIdFromSession($request);

    //     if ($line->user_id != $userId) {
    //         return $request->ajax()
    //             ? response()->json(['status' => 'error', 'message' => 'Unauthorized'], 403)
    //             : abort(403);
    //     }

    //     $line->delete();

    //     return $request->ajax()
    //         ? response()->json(['status' => 'ok', 'message' => 'Line deleted'])
    //         : redirect()->route('user.lines.create')->with('success', 'Line deleted');
    // }

    // public function restore(Request $request, $id)
    // {
    //     $userId = $this->userIdFromSession($request);

    //     $line = Line::onlyTrashed()
    //         ->where('line_id', $id)
    //         ->where('user_id', $userId)
    //         ->firstOrFail();

    //     $line->restore();

    //     return $request->ajax()
    //         ? response()->json(['status' => 'ok', 'message' => 'Line restored', 'line' => $line])
    //         : redirect()->route('user.lines.create')->with('success', 'Line restored');
    // }
    public function update(Request $request, $id)
{
    $userId = $this->userIdFromSession($request);

    $line = Line::where('line_id', $id)
                ->where('user_id', $userId)
                ->firstOrFail();

    $data = $request->validate([
        'line_name' => [
            'required',
            'string',
            'max:255',
            Rule::unique('lines', 'line_name')
                ->where(fn($q) => $q->where('user_id', $userId)->where('type', $line->type))
                ->ignore($line->line_id, 'line_id'),
        ],
    ]);

    $line->update(['line_name' => trim($data['line_name'])]);

    return response()->json(['status' => 'ok', 'message' => 'Updated', 'line' => $line]);
}
public function destroy(Request $request, $id)
{
    $userId = $this->userIdFromSession($request);

    $line = Line::where('line_id', $id)
                ->where('user_id', $userId)
                ->firstOrFail();

    $line->delete();

    return response()->json(['status' => 'ok', 'message' => 'Deleted']);
}
public function restore(Request $request, $id)
{
    $userId = $this->userIdFromSession($request);

    $line = Line::onlyTrashed()
        ->where('line_id', $id)
        ->where('user_id', $userId)
        ->firstOrFail();

    $line->restore();

    return response()->json(['status' => 'ok', 'message' => 'Restored', 'line' => $line]);
}
//   public function search(Request $request)
//     {
//         $query = $request->get('q', '');
//         if ($query != '') {
//             $lines = Line::where('name', 'like', "%$query%")->take(10)->get();
//             return response()->json($lines);
//         }
//         return response()->json([]);
//     }
}
