<?php

namespace App\Controllers;

use App\Controllers\Base\InternshipController as BaseInternshipController;

class InternshipController extends BaseInternshipController
{
    /**
     * Create new internship with multiple attachments
     * POST /internships
     */
    public function store()
    {
        $validated = $this->validate([
            'company_id' => 'required|integer',
            'student_id' => 'required|integer',
            'advisor_teacher_id' => 'integer',
            'start_date' => 'required',
            'end_date' => 'required',
            'report_file_path' => 'string|max:255',
            'advisor_score' => 'numeric',
            'attachments' => 'string',
            'status' => 'string|max:20',
            '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 Internship
        $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, 'internships', ['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, 'internships', ['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['attachments'] = json_encode($uploadedFiles);
        }

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

    /**
     * Update internship with multiple attachments
     * PUT/POST /internships/update
     */
    public function update()
    {
        $id = $this->request->param('id') ?: $this->request->input('id');
        $internship = $this->model->find($id);
        
        if (!$internship) {
            throw new \Exception('Internship not found', 404);
        }
        
        $validated = $this->validate([
            'company_id' => 'required|integer',
            'student_id' => 'required|integer',
            'advisor_teacher_id' => 'integer',
            'start_date' => 'required',
            'end_date' => 'required',
            'report_file_path' => 'string|max:255',
            'advisor_score' => 'numeric',
            'attachments' => 'string',
            'status' => 'string|max:20',
            '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, 'internships', ['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, 'internships', ['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 = $internship['attachments'] ?? '';
            $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($internship['attachments'])) {
                    $oldFiles = json_decode($internship['attachments'], true);
                    if (!is_array($oldFiles)) $oldFiles = [$internship['attachments']];
                    foreach ($oldFiles as $oldFile) {
                        $cleanPath = str_replace('uploads/', '', $oldFile);
                        \Wibiesana\Padi\Core\File::delete($cleanPath);
                    }
                }
                $filesToKeep = [];
            } else {
                $oldFilesStr = $internship['attachments'] ?? '';
                $filesToKeep = json_decode($oldFilesStr, true);
                if (!is_array($filesToKeep)) $filesToKeep = !empty($oldFilesStr) ? [$oldFilesStr] : [];
            }
        }

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

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