<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Advertisement;
use App\Models\Support;
use Illuminate\Http\Request;

class SupportController extends Controller
{
    public function support_request(Request $request)
    {

        $request->validate([
           
            'mobile' => 'required',
            'issue'  => 'required',
            'photo.*' => 'nullable|image|max:2048'  // each file max 2MB
        ]);
        // ✔ FIRST: Check mobile exists in advertisement table
        $mobileExists = Advertisement::where('phone', $request->mobile)->exists();

        // if (!$mobileExists) {
        //     return back()->withErrors(['mobileExists' => 'This mobile number is not registered in advertisement.'])->withInput();
        // }
        $imageUrls = [];

        if ($request->hasFile('photo')) {

            $photos = $request->file('photo');  // array of uploaded images

            // Debug: Check files (use only once)
            // dd($photos);

            foreach ($photos as $photo) {

                // Ensure folder exists
                $folderPath = public_path('uploads/support/');
                if (!file_exists($folderPath)) {
                    mkdir($folderPath, 0777, true);
                }

                // Unique filename
                $imageName = 'support_' . time() . '_' . uniqid() . '.' . $photo->getClientOriginalExtension();

                // Move file
                $photo->move($folderPath, $imageName);

                // Save URL (correct format)
                $imageUrls[] = $folderPath . $imageName;
            }
        }

        // Save as comma separated (or you can store as JSON)
        $commaSeparatedImages = implode(',', $imageUrls);
        //dd($commaSeparatedImages);
        // Insert into database
        Support::create([
            
            'mobile'     => $request->mobile,
            'issue'      => $request->issue,
            'photo'      => $commaSeparatedImages, // store all paths
            'created_at' => now(),
        ]);

        return back()->with('success', 'Request sent successfully.');
    }
}
