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

class Dashboard extends CI_Controller
{

  function __construct()
  {
    parent::__construct();
    // $this->load->database();
    $this->load->helper('url');
    $this->load->library('session');
    $this->load->model('dashboard_model');
    $this->load->model('common');
  }

  public function settings()
  {
    $data["settings"] = $this->common->readdatafromcollectionbetween("Settings");


    $this->template->template_render('settings', $data);
  }
  public function saveSettings($id)
  {
    $post = $this->input->post();
    $response = $this->common->updatedatamodel("Settings", $id, $post);
    if ($response) {
      $this->session->set_flashdata('successmessage', 'Settings has been updated');
    } else {
      $this->session->set_flashdata('warningmessage', 'Error! Some issue with firebase.Please try again');
    }

    redirect(base_url('dashboard/settings'));
  }

  // public function index()
  // {

  //   $sessionData = $this->session->userdata('session_data');
  //   $data['freelancers'] = $this->common->readnumberofdocumentsincollectionbetween('Users', 'userType', '=', 'Admin');
  //   $data['users'] = $this->common->readnumberofdocumentsincollectionbetween('Users', 'userType', '=', 'User');
  //   $data['totalUsers'] = $this->common->readnumberofdocumentsincollection('Users');
  //   $data['categories'] = $this->common->readnumberofdocumentsincollection('Categories');
  //   $users = $this->common->readdatafromcollectionwhereclause("Users", 'userRole', '=', 'user');
  //   $data['users'] = count($users);
  //   foreach ($users as $key => $user) {
  //     $timestamps[$key]    = $user['createdDate'];
  //   }
  //   array_multisort($timestamps, SORT_ASC, $users);
  //   $labels = array();

  //   $labels[0] = date('F', strtotime(date('F') . " - 3 months"));
  //   for ($i = 1; $i <= 5; $i++) {
  //     $timestamp = strtotime($labels[$i - 1] . ' + 1 month');
  //     $labels[$i] = date('F', $timestamp);
  //   }
  //   $labelStr = '';
  //   foreach ($labels as $label) {
  //     $labelStr .= '"' . $label . '", ';
  //   }

  //   $data['labelStr'] = $labelStr;
  //   $dataStr = '';
  //   for ($i = 0; $i < count($labels); $i++) {
  //     $num = 0;
  //     foreach ($timestamps as $timestamp) {
  //       if ($labels[$i] == date('F', $timestamp / 1000)) {
  //         $num += 0.2;
  //       }
  //     }
  //     $dataStr .= $num . ',';
  //   }
  //   $data['dataStr'] = $dataStr;

  //   $data['userdetails'] = $sessionData;






  //   $this->template->template_render('dashboard', $data);
  // }

  //   public function index()
  // {
  //     $this->load->library('session');
  //     $sessionData = $this->session->userdata('session_data');

  //     $data['freelancers'] = $this->common->readnumberofdocumentsincollectionbetween('Users', 'userType', '=', 'Admin');
  //     $data['users'] = $this->common->readnumberofdocumentsincollectionbetween('Users', 'userType', '=', 'User');
  //     $data['totalUsers'] = $this->common->readnumberofdocumentsincollection('Users');
  //     $data['categories'] = $this->common->readnumberofdocumentsincollection('Categories');

  //     $users = $this->common->readdatafromcollectionwhereclause("Users", 'userRole', '=', 'user');
  //     $data['users'] = count($users);

  //     foreach ($users as $key => $user) {
  //         $timestamps[$key] = $user['createdDate'];
  //     }

  //     array_multisort($timestamps, SORT_ASC, $users);

  //     $labels = [];
  //     $labels[0] = date('F', strtotime(date('F') . " - 3 months"));
  //     for ($i = 1; $i <= 5; $i++) {
  //         $timestamp = strtotime($labels[$i - 1] . ' + 1 month');
  //         $labels[$i] = date('F', $timestamp);
  //     }

  //     $labelStr = '';
  //     foreach ($labels as $label) {
  //         $labelStr .= '"' . $label . '", ';
  //     }
  //     $data['labelStr'] = $labelStr;

  //     $dataStr = '';
  //     for ($i = 0; $i < count($labels); $i++) {
  //         $num = 0;
  //         foreach ($timestamps as $timestamp) {
  //             if ($labels[$i] == date('F', $timestamp / 1000)) {
  //                 $num += 0.2;
  //             }
  //         }
  //         $dataStr .= $num . ',';
  //     }
  //     $data['dataStr'] = $dataStr;
  //     $data['userdetails'] = $sessionData;

  //     // ✅ Fetch only 'process' (new) orders
  //     try {
  //         $firebase = $this->firebase->init();
  //         $db = $firebase->createFirestore()->database();
  //         $vendorId = $sessionData['userId'];

  //         $ordersQuery = $db->collection('Orders')
  //                           ->where('vendorId', '==', $vendorId)
  //                           ->where('orderStatus', '==', 'process')
  //                           ->documents();

  //         $newOrders = [];
  //         $orderNumber = 1;

  //         foreach ($ordersQuery as $doc) {
  //             $newOrders[] = $this->processOrder($doc, $orderNumber++);
  //         }

  //         $data['newOrders'] = $newOrders;
  //     } catch (Exception $e) {
  //         $this->session->set_flashdata('warningmessage', 'Error loading orders: ' . $e->getMessage());
  //         $data['newOrders'] = [];
  //     }

  //     $this->template->template_render('dashboard', $data);
  // }
  public function index()
  {
    $this->load->library('session');
    $sessionData = $this->session->userdata('session_data');

    $data['freelancers'] = $this->common->readnumberofdocumentsincollectionbetween('Users', 'userType', '=', 'Admin');
    $data['users'] = $this->common->readnumberofdocumentsincollectionbetween('Users', 'userType', '=', 'User');
    $data['totalUsers'] = $this->common->readnumberofdocumentsincollection('Users');
    $data['categories'] = $this->common->readnumberofdocumentsincollection('Categories');

    $users = $this->common->readdatafromcollectionwhereclause("Users", 'userRole', '=', 'user');
    $data['users'] = count($users);

    foreach ($users as $key => $user) {
      $timestamps[$key] = $user['createdDate'];
    }

    array_multisort($timestamps, SORT_ASC, $users);

    $labels = [];
    $labels[0] = date('F', strtotime(date('F') . " - 3 months"));
    for ($i = 1; $i <= 5; $i++) {
      $timestamp = strtotime($labels[$i - 1] . ' + 1 month');
      $labels[$i] = date('F', $timestamp);
    }

    $labelStr = '';
    foreach ($labels as $label) {
      $labelStr .= '"' . $label . '", ';
    }
    $data['labelStr'] = $labelStr;

    $dataStr = '';
    for ($i = 0; $i < count($labels); $i++) {
      $num = 0;
      foreach ($timestamps as $timestamp) {
        if ($labels[$i] == date('F', $timestamp / 1000)) {
          $num += 0.2;
        }
      }
      $dataStr .= $num . ',';
    }
    $data['dataStr'] = $dataStr;
    $data['userdetails'] = $sessionData;

    // ✅ Fetch Order Data for Vendor
    try {
      $firebase = $this->firebase->init();
      $db = $firebase->createFirestore()->database();
      $vendorId = $sessionData['userId'];

      // --- New Orders (process only)
      $ordersQuery = $db->collection('Orders')
        ->where('vendorId', '==', $vendorId)
        ->where('orderStatus', '==', 'process')
        ->documents();

      $newOrders = [];
      $orderNumber = 1;

      foreach ($ordersQuery as $doc) {
        $newOrders[] = $this->processOrder($doc, $orderNumber++);
      }

      $data['newOrders'] = $newOrders;

      // --- Total Orders, Delivered Orders, Total Income
      $allOrdersQuery = $db->collection('Orders')
        ->where('vendorId', '==', $vendorId)
        ->documents();

      $totalOrders = 0;
      $deliveredOrders = 0;
      $totalIncome = 0;

      foreach ($allOrdersQuery as $doc) {
        if (!$doc->exists()) continue;

        $order = $doc->data();
        $totalOrders++;

        if (isset($order['orderStatus']) && $order['orderStatus'] === 'deliver') {
          $deliveredOrders++;
        }

        $price = isset($order['price']) ? $order['price'] : 0;
        $quantity = isset($order['totalQuantity']) ? $order['totalQuantity'] : 1;

        $totalIncome += $price * $quantity;
      }

      $data['totalOrders'] = $totalOrders;
      $data['deliveredOrders'] = $deliveredOrders;
      $data['totalIncome'] = 'AED ' . number_format($totalIncome, 2);

      // ✅ Fetch total products by tailor (vendor)
      $productsQuery = $db->collection('TailerServices')
        ->where('tailorId', '==', $vendorId)
        ->documents();

      $productCount = 0;
      foreach ($productsQuery as $productDoc) {
        if ($productDoc->exists()) {
          $productCount++;
        }
      }

      $data['totalProducts'] = $productCount;
    } catch (Exception $e) {
      $this->session->set_flashdata('warningmessage', 'Error loading orders: ' . $e->getMessage());
      $data['newOrders'] = [];
      $data['totalOrders'] = 0;
      $data['deliveredOrders'] = 0;
      $data['totalIncome'] = 'AED 0.00';
      $data['totalProducts'] = 0;
    }

    $this->template->template_render('dashboard', $data);
  }



  private function processOrder($doc, $orderNumber)
  {
    $orderData = $doc->data();
    return [
      'orderId' => $doc->id(),
      'orderNumber' => 'Order #' . $orderNumber,
      'image' => $orderData['productsData'][0]['image'] ?? base_url('assets/images/su1.png'),
      'date' => isset($orderData['date']) ? date('M d, Y', $orderData['date'] / 1000) : 'N/A',
      'status' => $orderData['orderStatus'],
      'price' => isset($orderData['price']) ? 'AED ' . number_format($orderData['price'], 2) : 'AED 0.00',
      'address' => implode(', ', array_filter([
        $orderData['address']['streetAddress1'] ?? '',
        $orderData['address']['city'] ?? '',
        $orderData['address']['state'] ?? ''
      ]))
    ];
  }

  // public function profile()
  // {
  //     $this->load->library('session');

  //     // Get session user ID
  //     $session_data = $this->session->userdata('session_data');
  //     if (!$session_data || !isset($session_data['userId'])) {
  //         $this->session->set_flashdata('warningmessage', 'User not authenticated.');
  //         redirect(base_url('login'));
  //     }

  //     $userId = $session_data['userId'];

  //     try {
  //         $firebase = $this->firebase->init();
  //         $firestore = $firebase->createFirestore();
  //         $db = $firestore->database();

  //         // Fetch user details from Firestore
  //         $userRef = $db->collection('Users')->document($userId);
  //         $userDoc = $userRef->snapshot();

  //         if (!$userDoc->exists()) {
  //             $this->session->set_flashdata('warningmessage', 'User data not found.');
  //             redirect(base_url('login'));
  //         }

  //         // Get user data
  //         $userData = $userDoc->data();



  //         // Pass data to view
  //         $this->template->template_render('profile', ['user' => $userData]);
  //     } catch (Exception $e) {
  //         $this->session->set_flashdata('warningmessage', 'Error fetching profile: ' . $e->getMessage());
  //         redirect(base_url('dashboard'));
  //     }
  // }

  // public function updateProfile()
  // {
  //     $this->load->library('form_validation');
  //     $this->load->library('session');

  //     header('Content-Type: application/json'); // Ensure JSON response

  //     // Get session user ID
  //     $session_data = $this->session->userdata('session_data');
  //     if (!$session_data || !isset($session_data['userId'])) {
  //         echo json_encode(['success' => false, 'message' => 'User not authenticated.']);
  //         return;
  //     }

  //     $userId = $session_data['userId'];

  //     $firebase = $this->firebase->init();
  //     $firestore = $firebase->createFirestore();
  //     $db = $firestore->database();

  //     $imageUrl = isset($session_data['u_image']) ? $session_data['u_image'] : '';

  //     // Handle Image Upload
  //     if (!empty($_FILES['profile_image']['name'])) {
  //         $upload_dir = FCPATH . 'uploads/users/' . $userId . '/';

  //         if (!is_dir($upload_dir)) {
  //             mkdir($upload_dir, 0755, true);
  //         }

  //         $file_name = uniqid() . '_' . $_FILES['profile_image']['name'];
  //         $file_path = $upload_dir . $file_name;

  //         if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $file_path)) {
  //             $imageUrl = base_url('uploads/users/' . $userId . '/' . $file_name);
  //         }
  //     }

  //     // Get tailor type selection
  //     $tailorType = $this->input->post('tailor_type');

  //     // Prepare Firestore Update Data
  //     $userData = [
  //         ['path' => 'name', 'value' => $this->input->post('name')],
  //         ['path' => 'startDate', 'value' => $this->input->post('start_date')],
  //         ['path' => 'shopTiming', 'value' => $this->input->post('shop_timing')],
  //         ['path' => 'shopLocation', 'value' => $this->input->post('shop_location')],
  //         ['path' => 'u_image', 'value' => $imageUrl],
  //         ['path' => 'tailorType', 'value' => $tailorType]
  //     ];

  //     try {
  //         // Update Firestore
  //         $db->collection('Users')->document($userId)->update($userData);

  //         // Update session data
  //         $session_data['name'] = $this->input->post('name');
  //         $session_data['startDate'] = $this->input->post('start_date');
  //         $session_data['shopTiming'] = $this->input->post('shop_timing');
  //         $session_data['shopLocation'] = $this->input->post('shop_location');
  //         $session_data['u_image'] = $imageUrl;
  //         $session_data['tailorType'] = $tailorType;

  //         $this->session->set_userdata('session_data', $session_data);

  //         echo json_encode(['success' => true, 'message' => 'Profile updated successfully!']);
  //     } catch (Exception $e) {
  //         echo json_encode(['success' => false, 'message' => 'Error updating profile: ' . $e->getMessage()]);
  //     }
  // }

  public function profile()
  {
    $this->load->library('session');
    $session_data = $this->session->userdata('session_data');
    if (!$session_data || !isset($session_data['userId'])) {
      $this->session->set_flashdata('warningmessage', 'User not authenticated.');
      redirect(base_url('login'));
    }

    $userId = $session_data['userId'];

    try {
      $firebase = $this->firebase->init();
      $firestore = $firebase->createFirestore();
      $db = $firestore->database();

      // Fetch user details
      $userRef = $db->collection('Users')->document($userId);
      $userDoc = $userRef->snapshot();

      if (!$userDoc->exists()) {
        $this->session->set_flashdata('warningmessage', 'User data not found.');
        redirect(base_url('login'));
      }

      // Get user data
      $userData = $userDoc->data();

      // Fetch all categories
      $categoriesQuery = $db->collection('Categories')->documents();
      $categories = [];
      foreach ($categoriesQuery as $category) {
        $categories[] = [
          'id' => $category->id(),
          'data' => $category->data(),
        ];
      }

      // Fetch existing tailor data if exists
      $tailorRef = $db->collection('Tailers')->document($userId);
      $tailorData = $tailorRef->snapshot()->exists() ? $tailorRef->snapshot()->data() : [];

      // Merge user and tailor data
      $mergedData = array_merge($userData, $tailorData);

      $this->template->template_render('profile', [
        'user' => $mergedData,
        'categories' => $categories
      ]);
    } catch (Exception $e) {
      $this->session->set_flashdata('warningmessage', 'Error fetching profile: ' . $e->getMessage());
      redirect(base_url('dashboard'));
    }
  }

  public function updateProfile()
  {
    $this->load->library('form_validation');
    $this->load->library('session');
    header('Content-Type: application/json');

    $session_data = $this->session->userdata('session_data');
    if (!$session_data || !isset($session_data['userId'])) {
      echo json_encode(['success' => false, 'message' => 'User not authenticated.']);
      return;
    }

    $userId = $session_data['userId'];
    $firebase = $this->firebase->init();
    $firestore = $firebase->createFirestore();
    $db = $firestore->database();
    $storage = $firebase->createStorage();
    $defaultBucket = $storage->getBucket();

    // Get current profile image
    $currentImageUrl = $session_data['u_image'] ?? '';

    // Handle file upload to Firebase Storage
    $imageUrl = $currentImageUrl;
    if (!empty($_FILES['profile_image']['name'])) {
      try {
        // Generate unique file path in Firebase Storage
        $file_name = 'Users/' . $userId . '/' . uniqid() . '_' . $_FILES['profile_image']['name'];

        // Upload file to Firebase Storage
        $uploadedFile = $defaultBucket->upload(
          file_get_contents($_FILES['profile_image']['tmp_name']),
          ['name' => $file_name, 'predefinedAcl' => 'publicRead']
        );

        if ($uploadedFile) {
          $imageUrl = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $file_name;

          // **🔥 Delete the old image if it exists in Firebase Storage**
          if (!empty($currentImageUrl)) {
            $parsedUrl = parse_url($currentImageUrl);
            if (isset($parsedUrl['path'])) {
              $oldFilePath = ltrim($parsedUrl['path'], '/');
              $oldObject = $defaultBucket->object($oldFilePath);
              if ($oldObject->exists()) {
                $oldObject->delete();
              }
            }
          }
        }
      } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Image upload failed: ' . $e->getMessage()]);
        return;
      }
    }

    // Get form data
    $postData = $this->input->post();
    $tailorType = $postData['tailor_type'] ?? '';

    // Update Users collection in Firestore
    $userUpdateData = [
      ['path' => 'name', 'value' => $postData['name']],
      // ['path' => 'startDate', 'value' => $postData['start_date']],
      ['path' => 'shopTiming', 'value' => $postData['shop_timing']],
      ['path' => 'lat', 'value' => $postData['lat']],
      ['path' => 'lng', 'value' => $postData['lng']],
      ['path' => 'state', 'value' => $postData['state']],
      ['path' => 'shopLocation', 'value' => $postData['shop_location']],
      ['path' => 'u_image', 'value' => $imageUrl], // Updated image URL
      ['path' => 'tailorType', 'value' => $tailorType]
    ];

    try {
      $db->collection('Users')->document($userId)->update($userUpdateData);

      // Prepare Tailors data
      $tailorData = [
        'categoryId' => $postData['categoryIds'] ?? [],
        'eta' => $postData['eta'],
        'gender' => ['male' => false, 'female' => false],
        'image' => $imageUrl, 
        // 'isVerified' => false,
        'name' => $postData['name'],
        'state' => $postData['state'],
        'shopLocation' => $postData['shop_location'],
        'id' => $userId
      ];

      // Set gender based on tailor type
      switch ($tailorType) {
        case "Men's Tailor":
          $tailorData['gender']['male'] = true;
          break;
        case "Women's Tailor":
          $tailorData['gender']['female'] = true;
          break;
        case "Both Men's & Women's Tailor":
          $tailorData['gender']['male'] = true;
          $tailorData['gender']['female'] = true;
          break;
      }

      // Update Tailors collection
      $db->collection('Tailers')->document($userId)->set($tailorData, ['merge' => true]);

      // Update session data
      $sessionUpdates = [
        'name' => $postData['name'],
        'startDate' => $postData['start_date'],
        'shopTiming' => $postData['shop_timing'],
        'shopLocation' => $postData['shop_location'],
        'u_image' => $imageUrl, // Updated image URL
        'tailorType' => $tailorType
      ];
      $this->session->set_userdata('session_data', array_merge($session_data, $sessionUpdates));

      echo json_encode(['success' => true, 'message' => 'Profile updated successfully!']);
    } catch (Exception $e) {
      echo json_encode(['success' => false, 'message' => 'Error updating profile: ' . $e->getMessage()]);
    }
  }







  public function categories()
  {

    $data['categories'] = $this->common->readdatafromcollectionwhereclause('Categories');
    $this->template->template_render('categories', $data);
  }

  public function addcategory()
  {

    $this->template->template_render('addcategory');
  }

  public function insertcategory()
  {

    $post = $this->input->post();
    $data['title'] = $post['title'];
    $response = $this->common->addnewdatamodel('Categories', $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Category added successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/categories'));
  }

  public function editcategory()
  {
    $id = $this->uri->segment(3);
    $data['id'] = $id;
    $data['category'] = $this->common->readdatadocument('Categories', $id);
    $this->template->template_render('addcategory', $data);
  }

  public function updatecategory()
  {
    $post = $this->input->post();
    $data['title'] = $post['title'];

    $response = $this->common->updatedatamodel('Categories', $post['id'], $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Category updated successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/categories'));
  }

  public function deletecategory()
  {
    $id = $this->uri->segment(3);

    $response = $this->common->deletedatamodel('Categories', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Category deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/categories'));
  }
}
