<?php

namespace App\Http\Controllers\v2019;

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

class CandidateApplicationController extends Controller
{
    public function store(Request $request)
    {
        // ✅ Validation (compatible with old Laravel)
        $this->validate($request, [
            'full_name' => 'required|string|max:255',
            'email_address' => 'required|email|max:255',
            'phone_number' => 'required|string|max:20',
            'current_location' => 'sometimes|string|max:255',
            'file_upload' => 'sometimes|mimes:pdf|max:2048', // ✅ fixed here
            'post_id' => 'sometimes|integer'
        ]);
 
        $filePath = ''; // default empty
 
        // ✅ LOCAL File Upload
        if ($request->hasFile('file_upload')) {
            $file = $request->file('file_upload');
 
            // unique filename
            $filename = time() . '_' . $file->getClientOriginalName();
 
            // destination path
            $destinationPath = "/home/steelmin/public_html/careerdoc/resume/";
 
            // create folder if not exist
            if (!file_exists($destinationPath)) {
                mkdir($destinationPath, 0777, true);
            }
 
            // move file
            $file->move($destinationPath, $filename);
 
            // file URL to save in DB
            $filePath = "https://www.steelmint.com/careerdoc/resume/" . $filename;
        }
 
        // ✅ Insert into database
        $insertedId = DB::table('tbl_bigmint_candidate_app_form')->insertGetId([
            'full_name' => $request->full_name,
            'email_address' => $request->email_address,
            'phone_number' => $request->phone_number,
            'current_location' => $request->current_location,
            'file_upload' => $filePath,
            'post_id' => $request->post_id ?? 0
        ]);
 
        // ✅ Response
        return response()->json([
            'status' => true,
            'message' => 'Candidate application submitted successfully',
            'id' => $insertedId,
            'file_url' => $filePath
        ], 201);
    }
}
