<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Info</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</head>

<style>

</style>


<body>
    <?php
    // Database connection
    include 'database/database.php';
    include 'database/data.php';
    include 'database/data.php';

    if (isset($_POST['update'])) {

        $barcode = $_POST['barcode'];
        $barcode_1 = $_POST['barcode_1'];
        $product_name = $_POST['product_name'];
        
        $product_name_ori = $_POST['product_name_ori']; // Correctly fetch the POST value


        $trans = $_POST['trans'];
        $currency_buy = $_POST['currency_buy'];

        $package_profit = $_POST['package_profit'];
        $unit_profit = $_POST['unit_profit'];
        $pieces_profit = $_POST['pieces_profit'];
        $catagories = $_POST['catagories'];

        $buy = $_POST['buy'];
        $unit = $_POST['unit'];
        $pieces = $_POST['pieces'];

        


    


        $productName = trim($_POST['product_name']); // Get the product name

    // Check if a file was uploaded
    if (isset($_FILES["image"]) && $_FILES["image"]["error"] === UPLOAD_ERR_OK) {
        // Define the target directory
        $targetDir = "uploads/";

        // Ensure the directory exists
        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0777, true); // Create the directory if it doesn't exist
        }

        // Get the file extension
        $fileType = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));

        // Construct the target file path with the product name
        $targetFilePath = $targetDir . $productName . '.' . $fileType;

        // Validate allowed file types
        $allowedTypes = array("jpg", "jpeg", "png", "gif");
        if (in_array($fileType, $allowedTypes)) {
            // Check file size and reduce if necessary
            $maxFileSize = 2 * 1024 * 1024; // 2MB
            $desiredFileSize = 100 * 1024; // 100KB

            // Temporary file path
            $tempPath = $_FILES["image"]["tmp_name"];

            // Reduce image size
            if ($_FILES["image"]["size"] > $maxFileSize) {
                // Load the image
                switch ($fileType) {
                    case 'jpg':
                    case 'jpeg':
                        $image = imagecreatefromjpeg($tempPath);
                        break;
                    case 'png':
                        $image = imagecreatefrompng($tempPath);
                        break;
                    case 'gif':
                        $image = imagecreatefromgif($tempPath);
                        break;
                    default:
                        $image = null;
                        break;
                }

                if ($image) {
                    // Resize the image
                    $originalWidth = imagesx($image);
                    $originalHeight = imagesy($image);
                    $newWidth = 800; // Set a new width (you can adjust)
                    $newHeight = ($originalHeight / $originalWidth) * $newWidth;

                    $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
                    imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

                    // Save the resized image with reduced quality
                    if ($fileType === 'jpg' || $fileType === 'jpeg') {
                        imagejpeg($resizedImage, $targetFilePath, 75); // 75% quality
                    } elseif ($fileType === 'png') {
                        imagepng($resizedImage, $targetFilePath, 6); // Compression level 6
                    } elseif ($fileType === 'gif') {
                        imagegif($resizedImage, $targetFilePath);
                    }

                    // Free memory
                    imagedestroy($image);
                    imagedestroy($resizedImage);

                    // echo "The image for <strong>" . htmlspecialchars($productName) . "</strong> has been uploaded and resized successfully.";
                    // echo "<br><a href='$targetFilePath'>View Uploaded image</a>";
                } else {
                    // echo "Unsupported image type.";
                }
            } else {
                // Move the file to the target directory if size is already acceptable
                if (move_uploaded_file($tempPath, $targetFilePath)) {
                    // echo "The image for <strong>" . htmlspecialchars($productName) . "</strong> has been uploaded successfully.";
                    // echo "<br><a href='$targetFilePath'>View Uploaded image</a>";
                } else {
                    // echo "Sorry, there was an error uploading your file.";
                }
            }
        } else {
            // echo "Invalid file format. Only JPG, JPEG, PNG, and GIF files are allowed.";
        }
    } else {
        // echo "No file was uploaded or there was an error during the upload.";
    }

    //Rename Image Name
    $extensions = ['jpg', 'jpeg', 'png', 'gif']; // Add more extensions if needed

    $oldFileName = '';
    $newFileName = '';
    $fileRenamed = false; // Track if renaming was successful
    
    foreach ($extensions as $ext) {
        $potentialOldFileName = 'uploads/' . $product_name_ori . '.' . $ext;
        if (file_exists($potentialOldFileName)) {
            $oldFileName = $potentialOldFileName;
            $newFileName = 'uploads/' . $product_name . '.' . $ext;
            break; // Exit the loop once the file is found
        }
    }
    
    if ($oldFileName && $newFileName) {
        // echo "Checking old file: $oldFileName<br>";
        // echo "Checking new file: $newFileName<br>";
        if (rename($oldFileName, $newFileName)) {
            // echo "File renamed successfully to: $newFileName<br>";
            $fileRenamed = true;
        } else {
            // echo "Error: File could not be renamed.<br>";
        }
    }
    
    if (!$fileRenamed) {
        // echo "Error: File does not exist for any of the following extensions: " . implode(', ', $extensions) . "<br>";
    }

    $rate_data = $_POST['rate'];
        
        $product_tables = [$product,$cargo_1];

        

        $sql = "SELECT * FROM ".$rate."";
        $result = $connection->query($sql);
        if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $baht = $row['baht']; 
            $yuan = $row['yuan']; 
            $dollar = $row['dollar']; 

            if($currency_buy == 'kyat'){ 
         
                $rate = '1';
            }else if($currency_buy == 'baht'){ 
               
                $rate = $baht;
                if ($rate == $rate_data){ 
                    $rate = $baht;
                }else{ 
                    $rate = $rate_data;
                }
              

            }else if($currency_buy == 'yuan'){ 
            
                $rate = $yuan;
                if ($rate == $rate_data){ 
                    $rate = $yuan;
                }else{ 
                    $rate = $rate_data;
                }
            

            }else if($currency_buy == 'dollar'){ 

                $rate = $dollar;
             

            }
            
            
            $package_price = ($buy+$trans);

            if ($unit > 0) {
                $unit_price = $package_price / $unit;
            } else {
                $unit_price = 0; // or handle the zero case as needed
            }
            
            if ($pieces > 0 && $unit_price > 0) {
                $pieces_price = $unit_price / $pieces;
            } else {
                $pieces_price = 0; // or handle the zero case as needed
            }

            function roundUpToNearestHundred($number) {
                return ceil($number / 1) * 1;
            }    
        
            $round_package_price = roundUpToNearestHundred($package_price+$package_profit);
            $round_unit_price = roundUpToNearestHundred($unit_price+$unit_profit);
            $round_pieces_price = roundUpToNearestHundred($pieces_price+$pieces_profit);
            
      
        foreach ($product_tables as $product_data) {
    
        //update barcode,name.....
        $sql = "UPDATE ".$product_data." SET product_name='$product_name',barcode='$barcode',barcode_1='$barcode_1',type='$catagories',unit='$unit',pieces='$pieces',rate='$rate',buy='$buy',trans='$trans',currency_buy='$currency_buy',round_package_price='$round_package_price',round_unit_price='$round_unit_price',round_pieces_price='$round_pieces_price',package_price='$package_profit',unit_price='$unit_profit',pieces_price='$pieces_profit' WHERE product_name='$product_name' or barcode='$barcode'";
        //$sql = "UPDATE product SET barcode='$barcode' WHERE id='$no'";
        if ($connection->query($sql) === TRUE) {
            // echo json_encode(['status' => 'success', 'message' => 'Record updated successfully']);
        } else {
            // echo json_encode(['status' => 'error', 'message' => 'Error updating record: ' . $connection->error]);
        }


    }
}
}
    }


    $product_name = $_POST['product_name'];
    $sql = "SELECT * FROM " . $product . " WHERE product_name = '$product_name'";
    $result = $connection->query($sql);
    $row = $result->num_rows > 0 ? $result->fetch_assoc() : null;

    if ($row) {
        $imageData = $row['image'];
    }
    ?>

    <!-- Modal -->
    <div style="margin-top:30px" class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
        <div class="modal-dialog">
            <div class="modal-content">

                <div class="modal-body">
                    <!-- Card -->
                    <div class="card shadow">
                        <div class="card-header bg-info text-white text-center">
                            <h5 class="card-title"><?php echo $row["product_name"]; ?></h5>
                        </div>
                        <div class="card-body">
                            <!-- Dynamically inserted Image -->
                            <div class="text-center mb-4">
                                <?php 
$extensions = ['jpg', 'jpeg', 'png', 'gif'];
$imagePath = '';

// Check for the correct file extension
foreach ($extensions as $ext) {
    $potentialPath = 'uploads/' . $row["product_name"] . '.' . $ext;
    if (file_exists($potentialPath)) {
        $imagePath = $potentialPath;
        break;
    }
}

// If the image path is found, display the image
if ($imagePath) {
    echo '<img src="' . $imagePath . '" class="img-fluid mb-3" alt="Sample Image" style="margin-left:auto;margin-right:auto;width:200px;">';
} else {
    echo 'Image not found.';
}

?>
                            </div>
                            <form action="product_photo_view.php" method="POST" enctype="multipart/form-data">
                                <table class="table table-borderless">

                            

                                    <tr>
                                        <th><label for="barcode" class="form-label">Barcode_1:</label></th>
                                        <td><input type="text" class="form-control" name="barcode" value="<?php echo $row["barcode"]; ?>"></td>
                                    </tr>

                                    <tr>
                                        <th><label for="barcode" class="form-label">Barcode_2:</label></th>
                                        <td><input type="text" class="form-control" name="barcode_1" value="<?php echo $row["barcode_1"]; ?>"></td>
                                    </tr>
                                    
                                    <tr style='display:none;'>
                                        <th><label for="barcode" class="form-label">ပစ္စည်းအမည်:</label></th>
                                      <th><input type="text" class="form-control" name="product_name_ori" value="<?php echo $row["product_name"]; ?>"></th>
                                    </tr>

                                    <tr>
                                        <th><label for="barcode" class="form-label">ပစ္စည်းအမည်:</label></th>
                                        <td><input type="text" class="form-control" name="product_name" value="<?php echo $row["product_name"]; ?>"></td>
                                    </tr>

                                    <tr>
    <th><label for="currency_buy" class="form-label">ပစ္စည်းအမျိုးစား :</label></th>
    <td>
        <select name="catagories" id="bankingInput" class="form-control">
            <option value="<?php echo $row['type']; ?>"><?php echo $row["type"]; ?></option>
            <?php
            // Query categories table
            $sql = "SELECT * FROM " . $catagories;
            $result = $connection->query($sql);
            if ($result && $result->num_rows > 0) {
                while ($row_cat = $result->fetch_assoc()) { // Use a separate variable to avoid overwriting $row
                    $name = $row_cat['type']; // Database column
                    echo '
                    <option value="' . $name . '">' . $name . '</option>
                    ';
                }
            }
            // Close the result and connection for categories
            if ($result) {
                $result->free(); // Free the result set
            }
            $connection->close(); // Close the connection
            ?>
        </select>
    </td>
</tr>
                                    
                                   
                                    <tr>
                                        <th><label for="currency_buy" class="form-label">ငွေအမျိုးအစား:</label></th>
                                        <td>
                                            <select name="currency_buy" id="bankingInput" class="form-control">
                                                <option value="<?php echo $row['currency_buy']; ?>"><?php echo $row["currency_buy"]; ?></option>
                                                <option value="kyat">kyat</option>
                                                <option value="baht">baht</option>
                                                <option value="yuan">yuan</option>
                                            </select>
                                        </td>
                                    </tr>

                                    
                                    <tr>
                                        <th><label for="trans" class="form-label">ငွေဈေးနှုန်း:</label></th>
                                        <td><input type="text" class="form-control" name="rate" value="<?php echo $row["rate"]; ?>"></td>
                                    </tr>

                                    <tr>
                                        <th><label for="trans" class="form-label">သယ်ဆောင်ခ:</label></th>
                                        <td><input type="text" class="form-control" name="trans" value="<?php echo $row["trans"]; ?>"></td>
                                    </tr>

                                    <tr>
                                        <th><label for="buy" class="form-label">ဖာလိုက်ဈေး:</label></th>
                                        <td><input type="text" class="form-control" name="buy" value="<?php echo $row["buy"]; ?>"></td>
                                    </tr>

                                    <tr>
                                        <th style="white-space: nowrap;color:red;"><label for="profit" class="form-label">ဖာ အမြတ်:</label></th>
                                        <td><input type="text" class="form-control" name="package_profit" value="<?php echo $row["package_price"]; ?>"></td>
                                    </tr>

                                    <tr>
                                        <th style="white-space: nowrap;color:red;"><label for="profit" class="form-label">ကဒ်/ထုပ် အမြတ်:</label></th>
                                        <td><input type="text" class="form-control" name="unit_profit" value="<?php echo $row["unit_price"]; ?>"></td>
                                    </tr>

                                    <tr>
                                        <th style="white-space: nowrap;color:red;"><label for="profit" class="form-label">ဗူး/ခု အမြတ်:</label></th>
                                        <td><input type="text" class="form-control" name="pieces_profit" value="<?php echo $row["pieces_price"]; ?>"></td>
                                    </tr>


                                    <tr>
                                        <th style="white-space: nowrap;"><label for="unit" class="form-label">ကဒ်/ထုပ် မူရင်း:</label></th>
                                        <td><input type="text" class="form-control" name="unit" value="<?php echo $row["unit"]; ?>"></td>
                                    </tr>

                                    <tr >
                                        <th style="white-space: nowrap;"><label for="pieces" class="form-label">ဗူး/ခု မူရင်း :</label></th>
                                        <td><input type="text" class="form-control" name="pieces" value="<?php echo $row["pieces"]; ?>"></td>
                                    </tr>

                                    <tr style="height: 50px;">
                                        <th> <label for="pwd" alt="hi"> ဓာတ်ပုံ:</label></th>
                                        <th><input type="file" class="form-control" name="image" id="image"></th>
                                   </tr>

                                   

                                    <tr>
                                        <td colspan="2">
                                            <button type="submit" name="update" class="btn btn-success w-100 mt-3">
                                                ပြင်ရန်
                                            </button>
                                        </td>
                                    </tr>

                                    </table>
                                 </form>

                                  <table class="table table-bordered"> 
                                    <tr>
                                        <td colspan="3" style="text-align:center">ရောင်းဈေး (<?php echo $row["currency_buy"]; ?>)</td>
                                    </tr>

                                    <tr>
                                        <td style="text-align:center">ဖာ</td>
                                        <td style="text-align:center">ကဒ်/ထုပ်</td>
                                        <td style="text-align:center">ဗူး/ခု</td>
                                    </tr>

                                    <tr>
                                        <td style="text-align:center"><?php echo $row["round_package_price"]; ?></td>
                                        <td style="text-align:center"><?php echo $row["round_unit_price"]; ?></td>
                                        <td style="text-align:center"><?php echo $row["round_pieces_price"]; ?></td>
                                    </tr>
                                  </table>

                                  <table class="table table-bordered"> 
                                    <tr>
                                        <td colspan="3" style="text-align:center">ရောင်းဈေး (kyat)</td>
                                    </tr>

                                    <tr>
                                        <td style="text-align:center">ဖာ</td>
                                        <td style="text-align:center">ကဒ်/ထုပ်</td>
                                        <td style="text-align:center">ဗူး/ခု</td>
                                    </tr>

                                    <?php 
if (!function_exists('forkyat')) {
    function forkyat($number) {
        return ceil($number / 100) * 100;
    }
}


                                    ?>

                                    <tr>
                                        <td style="text-align:center"><?php echo forkyat($row["round_package_price"]*$row['rate']); ?></td>
                                        <td style="text-align:center"><?php echo forkyat($row["round_unit_price"]*$row['rate']); ?></td>
                                        <td style="text-align:center"><?php echo forkyat($row["round_pieces_price"]*$row['rate']); ?></td>
                                    </tr>
                                  </table>

                                  <table class="table table-bordered"> 
                                    <tr>
                                        <td colspan="3" style="text-align:center">လက်ကျန်</td>
                                    </tr>

                                    <tr>
                                        <td style="text-align:center">ဖာ</td>
                                        <td style="text-align:center">ကဒ်/ထုပ်</td>
                                        <td style="text-align:center">ဗူး/ခု</td>
                                    </tr>

                                    <tr>
                                        <td style="text-align:center"><?php echo $row["package_exist"]; ?></td>
                                        <td style="text-align:center"><?php echo $row["unit_exist"]; ?></td>
                                        <td style="text-align:center"><?php echo $row["pieces_exist"]; ?></td>
                                    </tr>
                                  </table>


                                   

                                    
                              
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Script to show modal on page load -->
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const myModal = new bootstrap.Modal(document.getElementById('myModal'));
            myModal.show();
        });
    </script>
</body>

</html>
