<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class TamuFoto_model extends CI_Model {

    const UPLOAD_PATH = 'uploads/foto_tamu/';

    public function get_by_tamu($tamu_id) {
        $this->db->where('tamu_id', $tamu_id);
        $this->db->order_by('urutan', 'ASC');
        $this->db->order_by('created_at', 'ASC');
        return $this->db->get('tamu_foto')->result();
    }

    public function get_by_id($id) {
        $this->db->where('id', $id);
        return $this->db->get('tamu_foto')->row();
    }

    public function count_by_tamu($tamu_id) {
        $this->db->where('tamu_id', $tamu_id);
        return $this->db->count_all_results('tamu_foto');
    }

    /**
     * Upload satu atau banyak file sekaligus
     * $files = $_FILES['foto'] (bisa single atau multiple)
     * Kembalikan array ['ok'=>[], 'fail'=>[]]
     */
    public function upload_batch($tamu_id, $files, $label = null) {
        $upload_dir = FCPATH . self::UPLOAD_PATH;

        // Pastikan folder ada dan bisa ditulis
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        if (!is_writable($upload_dir)) {
            return ['ok' => [], 'fail' => ['Folder uploads/foto_tamu/ tidak bisa ditulis. Cek permission (chmod 755 atau 777)']];
        }

        $result = ['ok' => [], 'fail' => []];
        $urutan_start = $this->count_by_tamu($tamu_id);

        // Normalisasi $_FILES array (multiple input name="foto_tamu[]")
        $normalized = [];
        if (is_array($files['name'])) {
            for ($i = 0; $i < count($files['name']); $i++) {
                // Skip jika tidak ada file atau error
                if (empty($files['name'][$i])) continue;
                if ($files['error'][$i] === UPLOAD_ERR_NO_FILE) continue;
                $normalized[] = [
                    'name'     => $files['name'][$i],
                    'type'     => $files['type'][$i],
                    'tmp_name' => $files['tmp_name'][$i],
                    'error'    => $files['error'][$i],
                    'size'     => $files['size'][$i],
                ];
            }
        } else {
            // Single file (input tanpa [])
            if (!empty($files['name']) && $files['error'] === UPLOAD_ERR_OK) {
                $normalized[] = $files;
            }
        }

        foreach ($normalized as $idx => $file) {
            // Cek upload error dari PHP
            if ($file['error'] !== UPLOAD_ERR_OK) {
                $err_map = [
                    UPLOAD_ERR_INI_SIZE   => 'ukuran melebihi upload_max_filesize di php.ini',
                    UPLOAD_ERR_FORM_SIZE  => 'ukuran melebihi MAX_FILE_SIZE di form',
                    UPLOAD_ERR_PARTIAL    => 'file hanya terupload sebagian',
                    UPLOAD_ERR_NO_TMP_DIR => 'folder tmp tidak ditemukan',
                    UPLOAD_ERR_CANT_WRITE => 'gagal menulis ke disk',
                ];
                $result['fail'][] = $file['name'] . ' (' . ($err_map[$file['error']] ?? 'error ' . $file['error']) . ')';
                continue;
            }

            $ext     = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg','jpeg','png','webp','gif'];
            if (!in_array($ext, $allowed)) {
                $result['fail'][] = $file['name'] . ' (tipe tidak didukung)';
                continue;
            }
            if ($file['size'] > 5 * 1024 * 1024) {
                $result['fail'][] = $file['name'] . ' (ukuran > 5MB)';
                continue;
            }

            // Nama unik: pakai uniqid + microtime agar tidak bentrok meski upload bersamaan
            $new_name = 'tamu_' . $tamu_id . '_' . uniqid('', true) . '.' . $ext;

            if (move_uploaded_file($file['tmp_name'], $upload_dir . $new_name)) {
                $this->db->insert('tamu_foto', [
                    'tamu_id'     => $tamu_id,
                    'nama_file'   => $new_name,
                    'label'       => $label ?: null,
                    'urutan'      => $urutan_start + $idx,
                    'ukuran_byte' => $file['size'],
                    'created_at'  => date('Y-m-d H:i:s'),
                ]);
                $result['ok'][] = $new_name;
            } else {
                $result['fail'][] = $file['name'] . ' (move_uploaded_file gagal - cek permission folder)';
            }
        }

        return $result;
    }

    public function update_label($id, $label) {
        $this->db->where('id', $id);
        return $this->db->update('tamu_foto', ['label' => $label]);
    }

    public function delete($id) {
        $foto = $this->get_by_id($id);
        if ($foto) {
            $path = FCPATH . self::UPLOAD_PATH . $foto->nama_file;
            if (file_exists($path)) {
                @unlink($path);
            }
            $this->db->where('id', $id);
            return $this->db->delete('tamu_foto');
        }
        return false;
    }

    public function delete_by_tamu($tamu_id) {
        $fotos = $this->get_by_tamu($tamu_id);
        foreach ($fotos as $f) {
            $path = FCPATH . self::UPLOAD_PATH . $f->nama_file;
            if (file_exists($path)) @unlink($path);
        }
        $this->db->where('tamu_id', $tamu_id);
        return $this->db->delete('tamu_foto');
    }
}