<?php

namespace App\Controllers;

use App\Controllers\Base\StudentAchievementController as BaseStudentAchievementController;

class StudentAchievementController extends BaseStudentAchievementController
{
    /**
     * Create new student achievement with multiple certificates
     * POST /student-achievements
     */
    public function store()
    {
        $validated = $this->validate([
            'student_id' => 'required|integer',
            'achievement_name' => 'required|string|max:150',
            'category' => 'required|string|max:50',
            'level' => 'required|string|max:50',
            'achievement_date' => 'required',
            'notes' => 'string',
            'certificate_path' => 'string',
            'created_by' => 'integer',
            'updated_by' => 'integer'
        ]);
        
        $user = $this->request->user;
        $userId = $user ? (is_array($user) ? ($user['id'] ?? $user['user_id'] ?? null) : ($user->id ?? $user->user_id ?? null)) : null;
        if ($userId) {
            $validated['created_by'] = $userId;
            $validated['updated_by'] = $userId;
        }

        // Handle multiple file uploads for Certificate
        $uploadedFiles = [];
        $files = $_FILES['files'] ?? $_FILES['file'] ?? null;

        if ($files) {
            if (isset($files['name']) && is_array($files['name'])) {
                // Multiple files
                for ($i = 0; $i < count($files['name']); $i++) {
                    if ($files['error'][$i] === UPLOAD_ERR_OK) {
                        try {
                            $singleFile = [
                                'name' => $files['name'][$i],
                                'type' => $files['type'][$i],
                                'tmp_name' => $files['tmp_name'][$i],
                                'error' => $files['error'][$i],
                                'size' => $files['size'][$i],
                            ];
                            $path = \Wibiesana\Padi\Core\File::upload($singleFile, 'achievements', ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx']);
                            $uploadedFiles[] = 'uploads/' . $path;
                        } catch (\Exception $e) {
                            throw new \Exception("File upload failed at index {$i}: " . $e->getMessage(), 400);
                        }
                    }
                }
            } elseif (isset($files['error']) && $files['error'] === UPLOAD_ERR_OK) {
                // Single file
                try {
                    $path = \Wibiesana\Padi\Core\File::upload($files, 'achievements', ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx']);
                    $uploadedFiles[] = 'uploads/' . $path;
                } catch (\Exception $e) {
                    throw new \Exception("File upload failed: " . $e->getMessage(), 400);
                }
            }
        }

        if (!empty($uploadedFiles)) {
            $validated['certificate_path'] = json_encode($uploadedFiles);
        }

        try {
            $id = $this->model->create($validated);
            $this->model->with(['student:id,name']);
            $achievement = $this->model->find($id);
            return $this->created(\App\Resources\StudentAchievementResource::make($achievement));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to create student achievement', $e);
        }
    }

    /**
     * Update student achievement with multiple certificates
     * PUT/POST /student-achievements/update
     */
    public function update()
    {
        $id = $this->request->param('id') ?: $this->request->input('id');
        $achievement = $this->model->find($id);
        
        if (!$achievement) {
            throw new \Exception('Student Achievement not found', 404);
        }
        
        $validated = $this->validate([
            'student_id' => 'required|integer',
            'achievement_name' => 'required|string|max:150',
            'category' => 'required|string|max:50',
            'level' => 'required|string|max:50',
            'achievement_date' => 'required',
            'notes' => 'string',
            'certificate_path' => 'string',
            'created_by' => 'integer',
            'updated_by' => 'integer'
        ]);
        
        $user = $this->request->user;
        $userId = $user ? (is_array($user) ? ($user['id'] ?? $user['user_id'] ?? null) : ($user->id ?? $user->user_id ?? null)) : null;
        if ($userId) {
            $validated['updated_by'] = $userId;
        }

        // Handle multiple file uploads
        $newUploadedFiles = [];
        $files = $_FILES['files'] ?? $_FILES['file'] ?? null;

        if ($files) {
            if (isset($files['name']) && is_array($files['name'])) {
                // Multiple files
                for ($i = 0; $i < count($files['name']); $i++) {
                    if ($files['error'][$i] === UPLOAD_ERR_OK) {
                        try {
                            $singleFile = [
                                'name' => $files['name'][$i],
                                'type' => $files['type'][$i],
                                'tmp_name' => $files['tmp_name'][$i],
                                'error' => $files['error'][$i],
                                'size' => $files['size'][$i],
                            ];
                            $path = \Wibiesana\Padi\Core\File::upload($singleFile, 'achievements', ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx']);
                            $newUploadedFiles[] = 'uploads/' . $path;
                        } catch (\Exception $e) {
                            throw new \Exception("File upload failed at index {$i}: " . $e->getMessage(), 400);
                        }
                    }
                }
            } elseif (isset($files['error']) && $files['error'] === UPLOAD_ERR_OK) {
                // Single file
                try {
                    $path = \Wibiesana\Padi\Core\File::upload($files, 'achievements', ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx']);
                    $newUploadedFiles[] = 'uploads/' . $path;
                } catch (\Exception $e) {
                    throw new \Exception("File upload failed: " . $e->getMessage(), 400);
                }
            }
        }

        // Selective Deletion Logic
        $existingFilesInput = $this->request->input('existing_files');
        $filesToKeep = [];

        if ($existingFilesInput !== null) {
            $filesToKeep = json_decode($existingFilesInput, true);
            if (!is_array($filesToKeep)) {
                $filesToKeep = !empty($existingFilesInput) ? explode(',', $existingFilesInput) : [];
            }

            // Clean up files that are NOT in the keep list
            $oldFilesStr = $achievement['certificate_path'] ?? '';
            $oldFiles = json_decode($oldFilesStr, true);
            if (!is_array($oldFiles)) $oldFiles = !empty($oldFilesStr) ? [$oldFilesStr] : [];

            foreach ($oldFiles as $oldFile) {
                if (!in_array($oldFile, $filesToKeep)) {
                    $cleanPath = str_replace('uploads/', '', $oldFile);
                    \Wibiesana\Padi\Core\File::delete($cleanPath);
                }
            }
        } else {
            // Standard fallback behavior
            if (!empty($newUploadedFiles)) {
                if (!empty($achievement['certificate_path'])) {
                    $oldFiles = json_decode($achievement['certificate_path'], true);
                    if (!is_array($oldFiles)) $oldFiles = [$achievement['certificate_path']];
                    foreach ($oldFiles as $oldFile) {
                        $cleanPath = str_replace('uploads/', '', $oldFile);
                        \Wibiesana\Padi\Core\File::delete($cleanPath);
                    }
                }
                $filesToKeep = [];
            } else {
                $oldFilesStr = $achievement['certificate_path'] ?? '';
                $filesToKeep = json_decode($oldFilesStr, true);
                if (!is_array($filesToKeep)) $filesToKeep = !empty($oldFilesStr) ? [$oldFilesStr] : [];
            }
        }

        // Final Merge
        $finalFileList = array_merge($filesToKeep, $newUploadedFiles);
        if (!empty($finalFileList)) {
            $validated['certificate_path'] = json_encode($finalFileList);
        } else {
            $validated['certificate_path'] = null;
        }

        try {
            $this->model->update($id, $validated);
            $this->model->with(['student:id,name']);
            return \App\Resources\StudentAchievementResource::make($this->model->find($id));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to update student achievement', $e);
        }
    }
}