<?php

namespace App\Modules\Careers\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Careers\Models\Application;
use App\Modules\Careers\Models\Job;
use App\Modules\PLATFORM\Settings\Models\Company;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class ApiController extends Controller
{
    /**
     * Handle incoming job applications from external career pages.
     */
    public function apply(Request $request)
    {
        // 1. Validate the API Key
        $company = Company::where('api_key', $request->input('api_key'))->first();

        if (!$company) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid API key'
            ], 401);
        }

        // 2. Validate Request Data
        $validator = Validator::make($request->all(), [
            'job_title' => 'required|string|max:255',
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'nullable|string|max:50',
            'gender' => 'nullable|string|max:50',
            'age' => 'nullable|integer|min:16|max:100',
            'district' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:255',
            'highest_education' => 'nullable|string|max:255',
            'education' => 'nullable|string|max:255', // Alias just in case
            'highest_professional_qualification' => 'nullable|string|max:255',
            'experience_years' => 'nullable|string|max:50',
            'resume_file' => 'nullable|file|mimes:pdf,doc,docx|max:10240', // 10MB max
            'cover_letter' => 'nullable|string',
            'linkedin_url' => 'nullable|url|max:255',
            'portfolio_url' => 'nullable|url|max:255',
        ]);

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

    

        // 3. Duplicate Prevention (Same email + same job)
        $existing = Application::where('job_title', $request->job_title)
            ->where('email', $request->email)
            ->first();

        if ($existing) {
            return response()->json([
                'success' => false,
                'message' => 'This candidate has already applied for this position.'
            ], 409);
        }

        // 4. Handle Resume Upload
        $resumeFilename = null;
        if ($request->hasFile('resume_file')) {
            $file = $request->file('resume_file');
            $extension = $file->getClientOriginalExtension();
            $resumeFilename = Str::uuid() . '.' . $extension;
            // Store resume in /storage/app/resumes/
            $file->storeAs('resumes', $resumeFilename);
        }

        // 5. Create Application Record
        $application = Application::create([
            'job_title' => $request->job_title,
            'company_id' => $company->id,
            'candidate_name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'gender' => $request->gender,
            'age' => $request->age,
            'district' => $request->district,
            'city' => $request->city,
            'highest_education' => $request->highest_education ?? $request->education,
            'highest_professional_qualification' => $request->highest_professional_qualification,
            'experience_years' => $request->experience_years,
            'resume_file' => $resumeFilename,
            'cover_letter' => $request->cover_letter,
            'linkedin_url' => $request->linkedin_url,
            'portfolio_url' => $request->portfolio_url,
            'source' => 'api',
            'status' => 'new'
        ]);

        // Optional: Send Email Notification to HR could be dispatched here.

        return response()->json([
            'success' => true,
            'message' => 'Application submitted successfully'
        ], 201);
    }
}
