<?php

namespace App\Http\Controllers;

use App\Models\PrintJob;
use Illuminate\Http\Request;

class JobController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = PrintJob::orderBy('id', 'desc');

            if ($request->filled('job_status')) {
                $query->where('job_status', $request->job_status);
            }

            $data = $query->get();

            return datatables()->of($data)
                ->addIndexColumn()
                ->editColumn('booking_date', function ($row) {
                    return $row->booking_date ? date('d-m-Y', strtotime($row->booking_date)) : '-';
                })
                ->addColumn('action', function ($row) {
                    $showUrl = route('jobs.show', $row->id);
                    return '<a href="'.$showUrl.'" class="btn btn-sm btn-info text-white"><i class="fas fa-eye"></i></a>';
                })
                ->rawColumns(['action'])
                ->make(true);
        }

        return view('jobs.index');
    }

    public function show($job)
    {
        $job = PrintJob::with('booking')->findOrFail($job);
        return view('jobs.show', compact('job'));
    }

    public function updateStatus(Request $request, $job)
    {
        $request->validate([
            'job_status' => 'required|in:DTP Approved,Printing,Delivery',
        ]);

        try {
            $printJob = PrintJob::findOrFail($job);
            $printJob->job_status = $request->job_status;
            $printJob->save();

            return response()->json(['success' => true, 'message' => 'Job status updated successfully']);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error updating status: '.$e->getMessage(),
            ], 500);
        }
    }
}
