<?php

namespace App\Controllers;

use App\Core\Http\Request;
use App\Core\Response\Response;
use App\Repositories\BrandRepository;
use App\Repositories\MobileImageRepository;
use App\Repositories\MobileRepository;
use App\Repositories\VendorRepository;

class ApiAdmin
{
    public function login()
    {
        $request = new Request();
        $response = new Response();
        $vendor = new VendorRepository();
        try {
            $phone = $request::input("phone");
            $password = $request::input("password");
            $res = $vendor->findBYPhone($phone);
            if (!isset($res) or empty($res) or count($res) == 0) {
                $response->notFound("کاربری با این شماره موبایل پیدا نشد");
                $response->respond();
            }
            if (hash_verify($password, $res["password"])) {
                $response->ok($res);
            }else{
                $response->notAcceptable(" رمز اشتباه است ");
                $response->respond();
            }
            session_start();
            $_SESSION["user"] = $res;
            $response->respond();
        }catch (\Exception $e) {
            $response->serverError($e->getMessage());
        }

        $response->respond();
    }
    public function createVendor(){
        $request = new Request();
        $response = new Response();
        $vendor = new VendorRepository();
        try {
            $phoneTest = $vendor->findBYPhone($request::input("phone"));
            if (!isset($phoneTest) or empty($phoneTest) or count($phoneTest) == 0) {
                $vendor->create([
                    "name" => $request::input("name"),
                    "phone" => $request::input("phone"),
                    "vendor_name" => $request::input("vendor_name"),
                    "password" => hash_password($request::input("password")),
                ]);
                $response->ok($vendor);
            }else{
                $response->notAcceptable("شماره موبایل تکراری");
            }
        }catch (\Exception $e) {
            $response->serverError($e->getMessage());
        }
        $response->respond();
    }

    public function uploadFile()
    {
        header("Access-Control-Allow-Origin: http://mobilerepair.ir");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            http_response_code(200);
            exit();
        }
        $request = new Request();
        $response = new Response();
        $file = $request::file("file");
        $fileName = uploadFile($file);
        $response->ok([strstr($fileName, 'assets')]);
        $response->respond();
    }
    public function createProduct(){
        $request = new Request();
        $response = new Response();
        $mobile = new MobileRepository();
        $mimage = new MobileImageRepository();
        try {
            $id = $mobile->create([
                "name" => $request::input("name"),
                "brand_id" => $request::input("brand") ,
                "is_active" => $request::input("is_active"),
                "ram" => $request::input("ram"),
                "storage" => $request::input("storage"),
                "description" => $request::input("description"),
                "detail" => $request::input("detail"),
                "image_url" => $request::input("image"),
            ]);
            $images = json_decode($request::input("images"));
            foreach ($images as $image) {
                $mimage->create([
                    "mobile_id" => $id,
                    "image_url" => $image,
                ]);
            }
            $response->ok($id);
        }catch (\Exception $e) {
            $response->serverError($e->getMessage());
        }
        $response->respond();
    }
    public function searchMobile(): void
    {
        try {
            // ریپازیتوری و ابزارهای HTTP
            $repo     = new MobileRepository();
            $request  = new Request();
            $response = new Response();
            $brandre = new BrandRepository();

            // پارامترهای DataTables
            $start  = (int) $request::input('start', 0);
            $length = (int) $request::input('length', 10);
            $draw   = (int) $request::input('draw', 1);

            // فیلترها
            $brand   = (int) $request::input('brand', '');
            $ram     = trim($request::input('ram', ''));
            $storage = trim($request::input('storage', ''));
            $search  = trim($request::input('search', ''));

            // ساخت شرط WHERE و پارامترها
            $where  = "WHERE deleted_at IS NULL";
            $params = [];
            if ($brand !== 0 ) {
                $where           .= " AND brand_id = :brand";
                $params[':brand'] =$brand;
            }
            if ($ram !== '') {
                $where          .= " AND ram = :ram";
                $params[':ram']  = $ram;
            }
            if ($storage !== '') {
                $where              .= " AND storage = :storage";
                $params[':storage']  = $storage;
            }
            if ($search !== '') {
                $where               .= " AND (name LIKE :search OR description LIKE :search OR detail LIKE :search)";
                $params[':search']    = "%{$search}%";
            }

            // تعداد کل رکوردها (بدون فیلتر)
            $totalRow     = $repo->db->select("SELECT COUNT(*) AS cnt FROM `mobiles`");
            $recordsTotal = (int) $totalRow[0]['cnt'];

            // تعداد رکوردهای فیلترشده
            $countSql        = "SELECT COUNT(*) AS cnt FROM `mobiles` {$where}";
            $countRow        = $repo->db->select($countSql, $params);
            $recordsFiltered = (int) $countRow[0]['cnt'];

            // مرتب‌سازی
            $orderSql = "ORDER BY created_at DESC";

            // صفحه‌بندی — مقادیر عددی را مستقیماً جاسازی می‌کنیم
            $limitOffsetSql = "LIMIT {$length} OFFSET {$start}";

            // واکشی داده‌ها
            $dataSql = "
            SELECT
                id,
                name,
                is_vendor,
                is_active,
                brand_id,
                color_id,
                ram,
                storage,
                rate,
                description,
                detail,
                image_url,
                created_at,
                updated_at,
                deleted_at
            FROM `mobiles`
            {$where}
            {$orderSql}
            {$limitOffsetSql}
        ";
            $data  = [] ;
            $rows = $repo->db->select($dataSql, $params);
            foreach ($rows as $row) {

                $brand_name = $brandre->findById((int) $row['brand_id'])["name"];
                $a = ["brand" => $brand_name,];
                $data[] = array_merge($row, $a);
            }
            // خروجی JSON سازگار با DataTables
            $response->setBody([
                'draw'            => $draw,
                'recordsTotal'    => $recordsTotal,
                'recordsFiltered' => $recordsFiltered,
                'data'            => $data,
            ]);
            $response->respond();

        } catch (\Throwable $e) {
            http_response_code(500);
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode([
                'error'   => true,
                'message' => $e->getMessage(),
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
    }


}
