<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Client;
use Illuminate\Support\Facades\DB;

/**
 * API Controller for managing Client resources.
 * 
 * This controller handles RESTful API operations including:
 * - Listing, creating, updating, and deleting records via API
 * - JSON response format for all endpoints
 * - Validation and error handling
 * 
 * @package App\Http\Controllers\Api
 */
class ClientController extends Controller
{
    /**
     * Display a listing of the resource via API.
     * 
     * Returns a JSON response with all non-deleted records.
     * Supports eager loading of relations and custom ordering.
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status and data array
     */
    public function index(Request $request)
    {
        $query = Client::query();
        $query->latest();
        $data = $query->whereNull('deleted_at')->get();

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

    /**
     * Store a newly created resource in storage via API.
     * 
     * Validates the request data and creates a new record in the database.
     * Returns JSON response with success status and created record ID.
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status, message, and data
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'owner_name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'required|string|max:255',
            'logo' => 'nullable|string',
            'address' => 'required|string|max:255',
            'status' => 'required|string|max:255'
        ]);

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

        $table = new Client();
$currentDate = now();
            // Specify the storage path with the folder structure
            $storagePath = $currentDate->year . '/' . $currentDate->month . '/' . $currentDate->day . '/';
            
            // Specify the storage path with the folder structure
            if ($request->has('logo') && $request->filled('resized-logo') != '') {
            $storagePath = $currentDate->year . '/' . $currentDate->month . '/' . $currentDate->day . '/';
            $filename = $request->input('logo');
            uploadImage($request->input('resized-logo'), $filename);}
            $table->name = $request->input('name');
            $table->owner_name = $request->input('owner_name');
            $table->email = $request->input('email');
            $table->phone = $request->input('phone');
if ($request->has('logo') && $request->filled('resized-logo') != '') {            $table->logo = $storagePath.$request->input('logo');}
            $table->address = $request->input('address');
            $table->status = $request->input('status');

        $table->save();
        $max_id = $table->id;




        return response()->json([
            'success' => true,
            'message' => 'Record created successfully',
            'data' => ['id' => $max_id],
        ], 201);
    }

    /**
     * Display the specified resource via API.
     * 
     * Returns a JSON response with the requested record details.
     * Returns 404 if the record is not found or has been deleted.
     * 
     * @param Request $request
     * @param int $id The ID of the resource to retrieve
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status and data, or 404 if not found
     */
    public function show(Request $request, $id)
    {
        $query = Client::query();
        
        $row = $query->whereNull('deleted_at')->find($id);

        if (!$row) {
            return response()->json([
                'success' => false,
                'message' => 'Record not found',
            ], 404);
        }

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

    /**
     * Update the specified resource in storage via API.
     * 
     * Validates the request data and updates an existing record in the database.
     * Returns JSON response with success status and updated record ID.
     * Returns 404 if the record is not found or has been deleted.
     * 
     * @param Request $request
     * @param int $id The ID of the resource to update
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status, message, and data, or 404 if not found
     */
    public function update(Request $request, $id)
    {
        $table = Client::whereNull('deleted_at')->find($id);

        if (!$table) {
            return response()->json([
                'success' => false,
                'message' => 'Record not found',
            ], 404);
        }

        $validator = \Validator::make($request->all(), [
            'name' => 'nullable|string|max:255',
            'owner_name' => 'nullable|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:255',
            'logo' => 'nullable|string',
            'address' => 'nullable|string|max:255',
            'status' => 'nullable|string|max:255'
        ]);

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

$currentDate = now();
            // Specify the storage path with the folder structure
            $storagePath = $currentDate->year . '/' . $currentDate->month . '/' . $currentDate->day . '/';
            
            // Specify the storage path with the folder structure
            if ($request->has('logo') && $request->filled('resized-logo') != '') {
            $storagePath = $currentDate->year . '/' . $currentDate->month . '/' . $currentDate->day . '/';
            $filename = $request->input('logo');
            uploadImage($request->input('resized-logo'), $filename);}
            $table->name = $request->input('name');
            $table->owner_name = $request->input('owner_name');
            $table->email = $request->input('email');
            $table->phone = $request->input('phone');
if ($request->has('logo') && $request->filled('resized-logo') != '') {            $table->logo = $storagePath.$request->input('logo');}
            $table->address = $request->input('address');
            $table->status = $request->input('status');

        $table->update();





        return response()->json([
            'success' => true,
            'message' => 'Record updated successfully',
            'data' => ['id' => (int) $id],
        ], 200);
    }

    /**
     * Remove the specified resource from storage via API.
     * 
     * Soft deletes the specified record (can be restored later).
     * Returns JSON response with success status.
     * Returns 404 if the record is not found or has been deleted.
     * 
     * @param Request $request
     * @param int $id The ID of the resource to delete
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status and message, or 404 if not found
     */
    public function destroy(Request $request, $id)
    {
        $row = Client::whereNull('deleted_at')->find($id);

        if (!$row) {
            return response()->json([
                'success' => false,
                'message' => 'Record not found',
            ], 404);
        }

        $row->delete();

        return response()->json([
            'success' => true,
            'message' => 'Record deleted successfully',
        ], 200);
    }
}
