<?php

namespace App\Controllers\Owner;

use App\Controllers\BaseController;
use App\Models\ProductModel;
use App\Models\ProductImageModel;

class ProductPhoto extends BaseController
{
    protected $product;
    protected $image;

    public function __construct()
    {
        $this->product = new ProductModel();
        $this->image   = new ProductImageModel();
    }

    /*
    |--------------------------------------------------------------------------
    | Gallery Produk
    |--------------------------------------------------------------------------
    */

    public function index($id)
    {
        $product = $this->product->find($id);

        if (!$product) {

            return redirect()->to('/owner/product')
                    ->with('error','Produk tidak ditemukan.');

        }

        $data = [

            'title'   => 'Gallery Produk',

            'product' => $product,

            'images'  => $this->image
                            ->where('id_product',$id)
                            ->findAll()

        ];

        return view('owner/product/photo',$data);
    }

    /*
    |--------------------------------------------------------------------------
    | Upload
    |--------------------------------------------------------------------------
    */

    public function upload($id)
    {

        $file = $this->request->getFile('photo');

        if (!$file->isValid()) {

            return redirect()->back()
                    ->with('error','File tidak valid.');

        }

        if (!$file->isValid()) {

            return redirect()->back();

        }

        $newName = $file->getRandomName();

        $file->move(FCPATH.'uploads/products',$newName);

        $this->image->save([

            'id_product'=>$id,

            'image_url'=>$newName

        ]);

        return redirect()->back()
                ->with('success','Foto berhasil diupload.');

    }

    /*
    |--------------------------------------------------------------------------
    | Delete
    |--------------------------------------------------------------------------
    */

    public function delete($id)
    {

        $image = $this->image->find($id);

        if(!$image){

            return redirect()->back();

        }

        if(file_exists(FCPATH.'uploads/products/'.$image['image_url'])){

            unlink(FCPATH.'uploads/products/'.$image['image_url']);

        }

        $this->image->delete($id);

        return redirect()->back()
                ->with('success','Foto berhasil dihapus.');

    }

}