<?php

namespace App\Controllers;

use App\Models\SpinwheelModel;
use App\Models\SpinwheelSliceModel;

class Spinwheels extends AdminBaseController
{
    public $title = 'Spinwheels';
    public $menu = 'rewarder';
    public $submenu = 'spinwheels';

    public function index()
    {
        $this->permissionCheck('spinwheels_list');
        $rows = (new SpinwheelModel())->orderBy('id','desc')->findAll();
        return view('admin/spinwheels/list', compact('rows'));
    }

    public function add()
    {
        $this->permissionCheck('spinwheels_add');
        return view('admin/spinwheels/add');
    }

    public function save()
    {
        $this->permissionCheck('spinwheels_add');
        postAllowed();

        $spinwheelId = (new SpinwheelModel())->create([
            'title'      => post('title'),
            'description'=> post('description'),
            'spin_cost'  => (float) post('spin_cost'),
            'status'     => (int) post('status'),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        $slices = post('slices') ?? [];
        $labels = $slices['label'] ?? [];
        $values = $slices['reward_value'] ?? [];
        $weights= $slices['probability_weight'] ?? [];
        $colors = $slices['color'] ?? [];
        $files  = $this->request->getFileMultiple('slice_pictures') ?? [];

        $sliceModel = new SpinwheelSliceModel();
        $order = 1;
        foreach ($labels as $k => $label) {
            if (trim($label) === '') {
                continue;
            }
            $sliceId = $sliceModel->create([
                'spinwheel_id' => $spinwheelId,
                'label' => $label,
                'reward_value' => $values[$k] ?? null,
                'probability_weight' => isset($weights[$k]) ? (int) $weights[$k] : 0,
                'color' => $colors[$k] ?? '#FF0000',
                'status' => 1,
                'sort_order' => $order++,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            if (isset($files[$k]) && $files[$k]->isValid() && !$files[$k]->hasMoved()) {
                $ext = $files[$k]->getExtension();
                $uploadDir = FCPATH . 'uploads' . DIRECTORY_SEPARATOR . 'spinwheel_slices';
                if (!is_dir($uploadDir)) {
                    @mkdir($uploadDir, 0777, true);
                }
                $files[$k]->move($uploadDir, $sliceId . '.' . $ext, true);
                $sliceModel->updateById($sliceId, ['picture_type' => $ext]);
            }
        }

        return redirect()->to('spinwheels')->with('notifySuccess', 'Spinwheel created successfully');
    }

    public function edit($id = null)
    {
        $this->permissionCheck('spinwheels_edit');
        if (empty($id)) {
            return redirect()->to('spinwheels');
        }
        $row = (new SpinwheelModel())->getById($id);
        if (empty($row)) {
            return redirect()->to('spinwheels')->with('notifyError', 'Spinwheel not found');
        }
        $slices = (new SpinwheelSliceModel())->where('spinwheel_id',$id)->orderBy('sort_order','asc')->findAll();
        return view('admin/spinwheels/edit', compact('row','slices'));
    }

    public function update($id)
    {
        $this->permissionCheck('spinwheels_edit');
        postAllowed();

        (new SpinwheelModel())->update($id, [
            'title'      => post('title'),
            'description'=> post('description'),
            'spin_cost'  => (float) post('spin_cost'),
            'status'     => (int) post('status'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        $sliceModel = new SpinwheelSliceModel();
        $existing = $sliceModel->where('spinwheel_id',$id)->findAll();
        $existingIds = array_map(fn($s) => $s->id, $existing);

        $slices = post('slices') ?? [];
        $ids    = $slices['id'] ?? [];
        $labels = $slices['label'] ?? [];
        $values = $slices['reward_value'] ?? [];
        $weights= $slices['probability_weight'] ?? [];
        $colors = $slices['color'] ?? [];
        $files  = $this->request->getFileMultiple('slice_pictures') ?? [];

        $keptIds = [];
        $order = 1;
        foreach ($labels as $k => $label) {
            if (trim($label) === '') {
                continue;
            }
            $sid = isset($ids[$k]) && !empty($ids[$k]) ? (int)$ids[$k] : 0;
            $data = [
                'spinwheel_id' => $id,
                'label' => $label,
                'reward_value' => $values[$k] ?? null,
                'probability_weight' => isset($weights[$k]) ? (int) $weights[$k] : 0,
                'color' => $colors[$k] ?? '#FF0000',
                'status' => 1,
                'sort_order' => $order++,
                'updated_at' => date('Y-m-d H:i:s'),
            ];
            if ($sid > 0) {
                $sliceModel->updateById($sid, $data);
            } else {
                $data['created_at'] = date('Y-m-d H:i:s');
                $sid = $sliceModel->create($data);
            }
            $keptIds[] = $sid;

            if (isset($files[$k]) && $files[$k]->isValid() && !$files[$k]->hasMoved()) {
                $ext = $files[$k]->getExtension();
                $uploadDir = FCPATH . 'uploads' . DIRECTORY_SEPARATOR . 'spinwheel_slices';
                if (!is_dir($uploadDir)) {
                    @mkdir($uploadDir, 0777, true);
                }
                $files[$k]->move($uploadDir, $sid . '.' . $ext, true);
                $sliceModel->updateById($sid, ['picture_type' => $ext]);
            }
        }

        // Delete removed slices
        $toDelete = array_diff($existingIds, $keptIds);
        foreach ($toDelete as $delId) {
            $sliceModel->deleteById($delId);
        }

        return redirect()->to('spinwheels')->with('notifySuccess', 'Spinwheel updated successfully');
    }

    public function delete($id)
    {
        $this->permissionCheck('spinwheels_delete');

        // Delete slices first
        $sliceModel = new SpinwheelSliceModel();
        $sliceModel->where('spinwheel_id',$id)->delete();

        (new SpinwheelModel())->delete($id);
        return redirect()->to('spinwheels')->with('notifySuccess', 'Spinwheel deleted successfully');
    }
}
