<?php

namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\ChartIncome;
use App\Models\Client;
use CodeIgniter\HTTP\RequestInterface;


class Home extends BaseController
{
    public function index(): string
    {
        return view('templates/header')
        .view('dashboard')
        .view('templates/modal')
        .view('templates/footer');
    }
    public function chartIncome()
    {

        $year = $this->request->getGet('year') ?? date('Y');
        $ChartIncome = new ChartIncome();
        $Client = new Client();

        $totalIncomeMonthly = $ChartIncome->getTotalIncomeMonthly($year);
        $totalOrderMonthly = $ChartIncome->getTotalOrderperBulan($year);
        $chartclient = $Client->getRecentClient();
        $dataclient = $Client->gettotalRecentClient();
        $chartorders = $ChartIncome->getRecentOrders();
        $dataorders = $ChartIncome->dataRecentOrders();
        $client = $Client->getallclient();

        $data = [
            'totalIncomeMonthly' => $totalIncomeMonthly,
            'totalOrderMonthly' => $totalOrderMonthly,
            'chartclient' => $chartclient,
            'dataclient' => $dataclient,
            'recentorders' => $chartorders,
            'dataorders' => $dataorders,
            'client' => $client
        ];

        return $this->response->setJSON($data);
    }

    public function recent()
    {

        $Client = new Client();

        $data = $Client->getRecentClient();

        
        return $this->response->setJSON($data);
    }


    public function client()
    {
        $Client = new Client();
        $data = $Client->getallclient();

        
        return $this->response->setJSON($data);
    }

    public function clientbyid()
    {
        $Client = new Client();
        $client_key = $this->request->getGet('client_key');
        $client_key = $this->request->getPost('client_key');

        $data = $Client->getclientbyid($client_key);

        
        return $this->response->setJSON($data);
    }


    public function clientreg()
    {
        $Client = new Client();
        $request = \Config\Services::request();

        $data = json_decode($request->getBody(), true);

        // Define required fields
        $required_fields = ['username', 'client_name', 'password', 'client_phone', 'client_address', 'client_email'];

        // Check if all required fields are present in the data
        foreach ($required_fields as $field) {
            if (!isset($data[$field])) {
                // Return error response if any required field is missing
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Field ' . $field . ' is required.'
                ])->setStatusCode(400);
            }
        }
        $salt = bin2hex(random_bytes(16));

        $hashed_password = password_hash($data['password'] . $salt, PASSWORD_DEFAULT);

        $client_data = [
            'client_key' => bin2hex(random_bytes(12)), // Random 16 karakter
            'username' => $data['username'],
            'client_name' => $data['client_name'],
            'password' => $hashed_password,
            'client_phone' => $data['client_phone'],
            'client_address' => $data['client_address'],
            'client_email' => $data['client_email'],
            'active' => 1, // Anda dapat mengatur nilai default lain jika diperlukan
            'salt' => $salt,
            'date_created' => date('Y-m-d H:i:s'),
        ];

        $existingUser = $Client->getUserByUserNameOrPhone($data['username'], $data['client_phone']);

        if ($existingUser) {
            // Jika ada kesamaan, tampilkan pesan kesalahan
            return redirect()->to('/register')->with('error', 'Username atau nomor telepon sudah digunakan. Silakan coba lagi.');
        }
            // Buat akun pengguna dengan salt
            $result = $Client->createClient($client_data);

            if ($result) {
                // If client creation is successful, return success response
                return $this->response->setJSON([
                    'status' => 'success',
                    'message' => 'Client successfully created.'
                ])->setStatusCode(200);
            } else {
                // If client creation fails, return error response
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Failed to create client.'
                ])->setStatusCode(500);
            }

            // Redirect ke halaman login setelah pendaftaran berhasil
            return redirect()->to('/login')->with('success', 'Akun berhasil dibuat. Silakan login.');

    }
}
