<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Models\Book;
use App\Models\BookCopy;
use App\Models\Issue;

class IssueController extends Controller
{
    private function getStudents()
    {
        $students = [];
        $apiError = null;

        try {
            $response = Http::timeout(30)
                ->retry(3, 1000)
                ->post('https://bgnuerp.online/api/student_records_api', [
                    'token' => config('services.student_api.token')
                ]);

            if ($response->successful()) {
                $data = $response->json();

                \Log::debug('Raw API Response', ['response' => $data]);

                $rawStudents = $data['data'] ?? $data['students'] ?? $data;

                if (is_array($rawStudents)) {
                    $students = collect($rawStudents)->map(function ($student) {
                        return [
                            'sname' => $student['sname'] ?? '',
                            'srollno' => $student['srollno'] ?? '',
                        ];
                    })->toArray();
                } else {
                    \Log::error('Invalid student data format', ['data' => $data]);
                    $apiError = "API returned invalid data format";
                    $students = [];
                }
            } else {
                $apiError = "API request failed with status: " . $response->status();
                \Log::error($apiError, ['response' => $response->body()]);
            }
        } catch (\Exception $e) {
            $apiError = "API connection error: " . $e->getMessage();
            \Log::error($apiError);

            $students = [
                ['sname' => 'Fallback Student 1', 'srollno' => 'FALL123'],
                ['sname' => 'Fallback Student 2', 'srollno' => 'FALL456'],
            ];
        }

        return [
            'students' => $students,
            'apiError' => $apiError
        ];
    }

    public function create()
    {
        $studentData = $this->getStudents();

        return view('issues.issue_create', [
            'students' => $studentData['students'],
            'books' => Book::with(['copies' => fn($q) => $q->where('status', 'available')])->get(),
            'apiError' => $studentData['apiError']
        ]);
    }

   public function index()
{
    $studentData = $this->getStudents();

    $issuedBooks = Issue::with(['bookCopy.book'])
        ->orderBy('status') // Show returned books last
        ->orderBy('due_date', 'asc')
        ->paginate(10);

    // Map student names
    $issuedBooks->getCollection()->transform(function ($issue) use ($studentData) {
        $student = collect($studentData['students'])
            ->firstWhere('srollno', $issue->student_id);
        $issue->sname = $student['sname'] ?? $issue->sname ?? 'Unknown';
        return $issue;
    });

    return view('issues.issue_index', [
        'issuedBooks' => $issuedBooks,
        'apiError' => $studentData['apiError']
    ]);
}

public function store(Request $request)
{
    $request->validate([
        'student_id' => 'required',
        'book_copy_id' => 'required|exists:book_copies,id',
    ]);

    $studentData = $this->getStudents();
    $student = collect($studentData['students'])
        ->firstWhere('srollno', $request->student_id);

    $copy = BookCopy::findOrFail($request->book_copy_id);

    if ($copy->status !== 'available') {
        return back()->with('error', 'This book copy is not available');
    }

    $issue = Issue::create([
        'student_id' => $request->student_id,
        'sname' => $student['sname'] ?? 'Unknown',
        'book_copy_id' => $copy->id,
        'issue_date' => now(),
        'due_date' => now()->addDays(14),
        'status' => 'issued' // Set initial status
    ]);

    $copy->update(['status' => 'issued']);

    return redirect()->route('issues.index')->with('success', 'Book issued successfully');
}

public function return(Issue $issue)
{
    if ($issue->isReturned()) {
        return back()->with('error', 'This book is already returned');
    }

    $issue->update([
        'return_date' => now(),
        'status' => 'returned'
    ]);

    $issue->bookCopy->update(['status' => 'available']);

    return redirect()->route('issues.index')->with('success', 'Book returned successfully!');
}
public function studentHistory(Request $request)
{
    $studentId = $request->get('student_id');

    $history = Issue::with(['bookCopy', 'bookCopy.book'])
        ->where('student_id', $studentId)
        ->orderBy('issue_date', 'desc')
        ->get()
        ->map(function ($issue) {
            return [
                'book_name' => $issue->bookCopy->book->name,
                'copy_id' => $issue->bookCopy->id,
                'barcode' => $issue->bookCopy->barcode,
                'issue_date' => $issue->issue_date,
                'due_date' => $issue->due_date,
                'return_date' => $issue->return_date,
            ];
        });

    return response()->json($history);
}
}
