<?php

 include_once('connection.php');
 $dbConnection = new DbConnection();
 $user = new User($dbConnection->connection);

 // Function for login
 class User extends DbConnection {
    public function __construct($connection) {
        parent::__construct($connection);
    }

  public function check_login($email, $password) {
    $email = $this->escape_string($email);
    $password = $this->escape_string($password);
    $hashedPassword = md5($password); // Example: using MD5 for demonstration, not recommended for production

    $sql = "SELECT * FROM users WHERE email = '$email' AND password = '$hashedPassword'";
    $query = $this->connection->query($sql);

    if ($query && $query->num_rows > 0) {
        $row = $query->fetch_assoc(); // Fetch the entire row
        return $row; // Return the entire row of user data
    } else {
        return false;
    }
}
    public function escape_string($value) {
        return $this->connection->real_escape_string($value);
    }

    public function fetchonerecord($id){                   
        
        //var_dump($id);die;
        $onresult=mysqli_query($this->connection,"SELECT * FROM users WHERE id = $id");
                return $onresult;
                }

                public function update($userId, $oldPassword, $newPassword, $confirmPassword) {
                    // Check if the connection is successful
                    if (!$this->connection) {
                        throw new Exception('Database connection failed.');
                    }
                    
                    // Validate input parameters
                    if (empty($oldPassword) || empty($newPassword) || empty($confirmPassword)) {
                        throw new Exception('All fields are required.');
                    }
                    
                    // Check if the new password and confirm password match
                    if ($newPassword !== $confirmPassword) {
                        throw new Exception('New Password and Confirm Password do not match.');
                    }
                    
                    // Fetch the current password hash from the database
                    $query = "SELECT password FROM users WHERE id = ?";
                    $stmt = $this->connection->prepare($query);
                    $stmt->bind_param('i', $userId);
                    $stmt->execute();
                    $stmt->bind_result($currentPasswordHash);
                    $stmt->fetch();
                    $stmt->close();
            
                    // Check if the current password hash matches
                    if (!password_verify($oldPassword, $currentPasswordHash)) {
                        throw new Exception('Invalid Old Password.');
                    }
                    
                    // Hash the new password
                    $newPasswordHash = password_hash($newPassword, PASSWORD_DEFAULT);
            
                    // Update the password in the database
                    $query = "UPDATE users SET password = ? WHERE id = ?";
                    $stmt = $this->connection->prepare($query);
                    $stmt->bind_param('si', $newPasswordHash, $userId);
                    if (!$stmt->execute()) {
                        throw new Exception('Error updating the password: ' . $this->connection->error);
                    }
                    $stmt->close();
                    
                    // Return true if the password update was successful
                    return true;
                }
            
                

 }

 class NewOrder extends DbConnection {
    public function order($order_id, $c_uid, $category, $product, $variation, $product_id, $price, $items ,$total_amount, $payment_reference) {     
         // Escape the value to prevent SQL injection
    
$query = "INSERT INTO order_summery(order_id, cuid, category, product, variation, product_id, price, items ,total_price, payment_reference) VALUES ('$order_id','$c_uid', '$category', '$product', '$variation', '$product_id' ,'$price', '$items','$total_amount', '$payment_reference')";
        mysqli_query($this->connection, $query);
        
        return 1;
        // Registration successful
    }
    

 public function generateSequentialNumber() {
    // Retrieve the last generated number from the database for today's date
    $currentDate = date('Y-m-d'); // Correct format to match 'created_on' field
    $lastNumberQuery = mysqli_query($this->connection, "SELECT MAX(order_id) as last_number FROM order_summery WHERE DATE(created_on) = '$currentDate'");
    $lastNumberResult = mysqli_fetch_assoc($lastNumberQuery);
    $lastNumber = $lastNumberResult['last_number'];

    // Parse the last number and increment it by 1
    if ($lastNumber) {
        $lastNumberParts = explode('/', $lastNumber);
        $lastSequentialNumber = end($lastNumberParts);
        $number = $lastSequentialNumber + 1;
    } else {
        // If no previous number exists for today's date, start from 1
        $number = 1;
    }

    // Return the generated number with the current date
    return $currentDate . '/' . $number;
}
    

    public function SalesList($c_uid, $category, $product, $variation, $price, $traullyNumber) {     
        
   
       $query = "INSERT INTO order_list(c_uid, category, product, variation, price, traully_number) VALUES ('$c_uid', '$category', '$product', '$variation', '$price', '$traullyNumber')";
       mysqli_query($this->connection, $query);
       
       return 1;
       // Registration successful
   }

   public function Procurement($category, $product, $variation, $price) {     
    // Escape the value to prevent SQL injection

   $query = "INSERT INTO procurement(category, product, variation, price) VALUES ('$category', '$product', '$variation', '$price')";
   mysqli_query($this->connection, $query);
   
   return 1;
   // Registration successful
}

    public function ArrivalStore($category, $product, $variation, $product_id, $price, $quantity,$quality_check_pass,$quality_check_no){
        
        $query = "INSERT INTO arrival_store(category, product, variation,product_id, price, quantity,quality_check_pass, quality_check_no) VALUES ('$category', '$product', '$variation', '$price','$quantity','$quality_check_pass','$quality_check_no')";
        mysqli_query($this->connection,$query);
    return 1;

}

  public function ApprovedStock($category, $product, $variation, $price, $quantity){
      $query = "INSERT INTO  warehouse(category, product, variation, price, quantity)VALUES('$category', '$product', '$variation', '$price', '$quantity')";
           mysqli_query($this->connection,$query);
           return 1;
  }


    public function Stockfetchonerecord($id, $product){
        $stmt = $this->connection->prepare("SELECT * FROM product_variation WHERE id = ? AND product = ?");
        $stmt->bind_param("is", $id, $product); // 'i' for integer, 's' for string
        $stmt->execute();
        return $stmt->get_result();
    }
    

    
 
    public function updateProduct($product, $category, $variation, $product_id, $price, $quantity, $id) {
        // Prepare and execute the update queries
        // $updateProductQuery = "UPDATE `product` SET `category`=?, `product`=? WHERE `id`=?";
        // $stmt = $this->connection->prepare($updateProductQuery);
        // $stmt->bind_param('ssi', $category, $product, $id);
        // $productUpdateResult = $stmt->execute();
    
        $updateVariationQuery = "UPDATE `product_variation` SET `product`=?, `variation`=?, `product_id`=?, `price`=?, `quantity`=? WHERE `id`=?";
        $stmt = $this->connection->prepare($updateVariationQuery);
        $stmt->bind_param('sssiii', $product, $variation, $product_id, $price, $quantity, $id);
        $variationUpdateResult = $stmt->execute();
    
        // Return true if both queries were successful
        return  $variationUpdateResult;
    }
    
 }
?>