<?php

// app/Http/Controllers/StudentsController.php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Http;

use App\Models\Student;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

class StudentsController extends Controller
{
    // GET /students?school=CODE  (must match logged-in user)
    public function index(Request $request)
    {
        $authSchool = $request->user()->username;
        $school = $request->query('school', $authSchool);

        if ($school !== $authSchool) {
            return response()->json(['error' => 'Forbidden: Invalid school code'], 403);
        }

        return Student::where('school', $school)->orderByDesc('date')->get();
    }

    // GET /students/{id}
    public function show(Request $request, $id)
    {
        $school = $request->user()->username;
        $student = Student::where('id', $id)->where('school', $school)->first();

        if (!$student) {
            return response()->json(['error' => 'Student not found'], 404);
        }
        return $student;
    }


    public function store(Request $request)
    {
        $school = $request->user()->username;

        $validated = $request->validate([
            'exam'   => 'required|string',
            'fname'  => 'required|string',
            'mname'  => 'nullable|string',
            'lname'  => 'required|string',
            'sex'    => 'required|in:Male,Female,Other',
            'bdate'  => 'required|date',
            'pob'    => 'nullable|string',
            'country'=> 'nullable|string',
            'disable'=> 'required|in:Yes,No',
            'disability'=>'nullable|string',
            'status' => 'required|in:0,1',
            'photo'  => 'nullable|image',
        ]);

        return DB::transaction(function () use ($request, $school, $validated) {

            do {
                $st_id = (string) random_int(1000000000, 9999999999);
            } while (Student::where('st_id', $st_id)->exists());

            $count = Student::where('school', $school)->lockForUpdate()->count();
            if ($count >= 999) {
                return response()->json(['error' => 'Maximum number of students (999) reached for this school'], 400);
            }

            $st_code = str_pad((string)($count + 1), 3, '0', STR_PAD_LEFT);
            $stud_id = "{$school}{$st_code}";

            $filename = null;
            if ($request->hasFile('photo')) {
                $photoFile = $request->file('photo');

                // 1️⃣ Save locally
                $path = $photoFile->store('photo', 'public'); // storage/app/public/photo
                $filename = basename($path);

                // 2️⃣ Upload to remote domain
                $remoteUrl = 'https://waec.hakapps.com/images'; // your external URL
                $response = Http::attach(
                    'photo', file_get_contents($photoFile->getRealPath()), $filename
                )->post($remoteUrl, [
                    'student_id' => $stud_id, // optional extra data
                ]);

                if (!$response->successful()) {
                    throw new \Exception('Failed to upload photo to remote domain');
                }
            }

            $student = Student::create([
                'st_id'  => $st_id,
                'exam'   => $validated['exam'],
                'school' => $school,
                'st_code'=> $st_code,
                'stud_id'=> $stud_id,
                'fname'  => $validated['fname'],
                'mname'  => $validated['mname'] ?? null,
                'lname'  => $validated['lname'],
                'sex'    => $validated['sex'],
                'bdate'  => $validated['bdate'],
                'pob'    => $validated['pob'] ?? null,
                'country'=> $validated['country'] ?? null,
                'disable'=> $validated['disable'],
                'disability'=> $validated['disability'] ?? null,
                'photo'  => $filename,
                'status' => $validated['status'],
                'date'   => now(),
            ]);

            return response()->json($student, 201);
        });
    }


    // PUT /students/{id}
    public function update(Request $request, $id)
    {
        $school = $request->user()->username;

        $student = Student::where('id', $id)->where('school', $school)->first();
        if (!$student) {
            return response()->json(['error' => 'Student not found or unauthorized'], 404);
        }

        $validated = $request->validate([
            'exam'   => 'sometimes|string',
            'fname'  => 'sometimes|string',
            'mname'  => 'sometimes|nullable|string',
            'lname'  => 'sometimes|string',
            'sex'    => 'sometimes|in:Male,Female,Other',
            'bdate'  => 'sometimes|date',
            'pob'    => 'sometimes|nullable|string',
            'country'=> 'sometimes|nullable|string',
            'disable'=> 'sometimes|in:Yes,No',
            'disability'=>'sometimes|nullable|string',
            'status' => 'sometimes|in:0,1',
            'photo'  => 'sometimes|nullable|image',
        ]);

        if ($request->hasFile('photo')) {
            // optional: delete old file
            if ($student->photo) {
                @Storage::disk('public')->delete("photo/{$student->photo}");
            }
            $path = $request->file('photo')->store('photo', 'public');
            $validated['photo'] = basename($path);
        }

        $validated['date'] = now();
        $student->update($validated);

        return $student->fresh();
    }

    // DELETE /students/{id}
    public function destroy(Request $request, $id)
    {
        $school = $request->user()->username;
        $student = Student::where('id', $id)->where('school', $school)->first();

        if (!$student) {
            return response()->json(['error' => 'Student not found'], 404);
        }

        if ($student->photo) {
            @Storage::disk('public')->delete("photo/{$student->photo}");
        }

        $student->delete();
        return response()->json(['message' => 'Student deleted successfully']);
    }

    // GET /student/search/{query}
    public function search(Request $request, $query)
    {
        $school = $request->user()->username;
        $like = "%{$query}%";

        return Student::where('school', $school)
            ->where(function ($q) use ($like) {
                $q->where('stud_id', 'like', $like)
                    ->orWhere('fname', 'like', $like)
                    ->orWhere('mname', 'like', $like)
                    ->orWhere('lname', 'like', $like);
            })
            ->orderByDesc('date')
            ->get();
    }
}
