<?php

namespace App\Http\Controllers;

use App\Models\Student_cards_template;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class StudentCardController extends Controller
{
    public function cardCustomize(string $template_name)
    {
        $card = student_cards_template::where('template_name', $template_name)->first();
        return view('stdCard.cardCustm', compact('card'));
    }

    public function cardCustomizeStore(string $template_name, Request $request)
    {
        // Validate the request
        $request->validate([
            'background_color' => 'required|string',
            'text_color'       => 'required|string',
            'logo'             => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        // Start a database transaction
        DB::beginTransaction();

        try {
            // Find the card template
            $card = student_cards_template::where('template_name', $template_name)->first();

            if (! $card) {
                throw new \Exception('Card template not found.');
            }

            // Handle logo upload
            $logoPath = null;
            if ($request->hasFile('logo')) {
                // Store the new logo
                $logoPath = $request->file('logo')->store('student_cards/logo', 'public');

                // Delete the old logo if it exists
                if ($card->logo && Storage::disk('public')->exists($card->logo)) {
                    Storage::disk('public')->delete($card->logo);
                }
            }

            // Update the card template
            $card->update([
                'background_color' => $request->background_color,
                'text_color'       => $request->text_color,
                'logo'             => $logoPath ?? $card->logo, // Keep the old logo if no new logo is uploaded
            ]);

            // Update logos for all other templates (if a new logo is uploaded)
            /* if ($logoPath) {
                $cards = student_cards_template::where('template_name', '!=', $template_name)->get();
                foreach ($cards as $otherCard) {
                    $otherCard->update([
                        'logo' => $logoPath,
                    ]);
                }
            } */

            // Commit the transaction
            DB::commit();

            return redirect()->back()->with('success', 'Card template updated successfully!');
        } catch (\Exception $e) {
            // Rollback the transaction on error
            DB::rollBack();

            // Log the error
            Log::error('Error updating card template: ' . $e->getMessage());

            // Delete the newly uploaded logo if the transaction fails
            if (isset($logoPath) && Storage::disk('public')->exists($logoPath)) {
                Storage::disk('public')->delete($logoPath);
            }

            return redirect()->back()->with('error', 'Failed to update card template. Please try again.');
        }
    }
}
