<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use App\Models\Project;
use Illuminate\Support\Facades\Validator;

class ProjectController extends Controller
{
    // Show form and list of projects
    public function create_project()
    {
        $projects = Project::all();
        return view('maintanance.suppliers.create_projects', compact('projects'));
    }

    // Store new project
    public function store_project(Request $request)
    {
        try {
            $request->validate([
                'code' => 'required|string|max:255|unique:projects,code',
                'name' => 'required|string|max:255',
                'description' => 'nullable|string|max:500',
            ], [
                'code.unique' => 'The project code already exists. Please choose a different one.',
            ]);

            $project = new Project();
            $project->code = $request->code;
            $project->name = $request->name;
            $project->description = $request->description;
            $project->save();

            return redirect()->route('projects.create')->with('success', 'Project created successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Edit existing project
    public function edit_project(Request $request)
    {
        try {
            $request->validate([
                'id' => 'required|integer|exists:projects,id',
                'code' => 'required|string|max:255',
                'name' => 'required|string|max:255',
                'description' => 'nullable|string|max:500',
            ]);

            $project = Project::findOrFail($request->id);
            $project->code = $request->code;
            $project->name = $request->name;
            $project->description = $request->description;
            $project->save();

            return redirect()->route('projects.create')->with('success', 'Project updated successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Delete project
    public function delete_project($id)
    {
        try {
            $project = Project::findOrFail($id);
            $project->delete();

            return redirect()->route('projects.create')->with('success', 'Project deleted successfully.');
        } catch (Exception $e) {
            return redirect()->route('projects.create')->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }
}
