<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('includes/dbconnection.php');
if (strlen($_SESSION['imsaid']==0)) {
  header('location:logout.php');
  } else{
    if(isset($_POST['submit']))
  {
    $eid=$_GET['editid'];
    $brandname=trim($_POST['brandname']);
    $status = isset($_POST['status']) ? '1' : '0'; // Fix checkbox handling
    $brandicon=trim($_POST['brandicon']);
    
    // Debug: Check if form data is being received
    echo "<script>console.log('Form submitted - Brand: $brandname, Status: $status, Icon: $brandicon');</script>";
    
    // Create upload directory if it doesn't exist
    $upload_dir = 'images/brand_icons/';
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    // Get current icon from database
    $current_icon_query = mysqli_query($con, "SELECT BrandIcon FROM tblbrand WHERE ID='$eid'");
    $current_icon_row = mysqli_fetch_array($current_icon_query);
    $current_icon = $current_icon_row['BrandIcon'];
    
    // Handle file upload if provided
    $icon_path = $current_icon; // Keep current icon by default
    if (!empty($_FILES['icon_file']['name'])) {
        $file_name = $_FILES['icon_file']['name'];
        $file_tmp = $_FILES['icon_file']['tmp_name'];
        $file_size = $_FILES['icon_file']['size'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $allowed_extensions = array('png', 'jpg', 'jpeg', 'gif', 'svg');
        
        echo "<script>console.log('File upload - Name: $file_name, Size: $file_size, Ext: $file_ext');</script>";
        
        if (in_array($file_ext, $allowed_extensions)) {
            if ($file_size < 5000000) { // 5MB limit
                $new_file_name = preg_replace('/[^a-zA-Z0-9]/', '_', $brandname) . '_' . time() . '.' . $file_ext;
                $upload_path = $upload_dir . $new_file_name;
                
                if (move_uploaded_file($file_tmp, $upload_path)) {
                    // Delete old icon file if it exists and is not an emoji
                    if (!empty($current_icon) && !preg_match('/[\x{1F600}-\x{1F64F}]|[\x{1F300}-\x{1F5FF}]|[\x{1F680}-\x{1F6FF}]|[\x{1F1E0}-\x{1F1FF}]|[\x{2600}-\x{26FF}]|[\x{2700}-\x{27BF}]/u', $current_icon)) {
                        $old_file_path = $current_icon;
                        if (file_exists($old_file_path)) {
                            unlink($old_file_path);
                        }
                    }
                    $icon_path = 'images/brand_icons/' . $new_file_name;
                    echo "<script>console.log('File uploaded successfully: $icon_path');</script>";
                } else {
                    echo '<script>alert("Failed to upload file!")</script>';
                }
            } else {
                echo '<script>alert("File size too large! Maximum 5MB allowed.")</script>';
            }
        } else {
            echo '<script>alert("Invalid file type! Only PNG, JPG, JPEG, GIF, SVG allowed.")</script>';
        }
    } else if (!empty($brandicon)) {
        // Use emoji icon if provided and no file uploaded
        $icon_path = $brandicon;
    }
     
    $query=mysqli_query($con, "UPDATE tblbrand SET BrandName='$brandname', BrandIcon='$icon_path', Status='$status' WHERE ID=$eid");
    if ($query) {
   
    echo '<script>alert("Brand has been updated successfully.")</script>';
    echo '<script>window.location.href = "manage-brand.php"</script>';
  }
  else
    {
     echo '<script>alert("Something Went Wrong. Please try again")</script>';
     echo '<script>console.log("SQL Error: ' . mysqli_error($con) . '");</script>';
    }

  
}
  ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mobile Store Management System|| Update Brand</title>
<?php include_once('includes/cs.php');?>
</head>
<body>

<!--Header-part-->
<?php include_once('includes/header.php');?>
<?php include_once('includes/sidebar.php');?>


<div id="content">
<div id="content-header">
  <div id="breadcrumb"> <a href="dashboard.php" title="Go to Home" class="tip-bottom"><i class="icon-home"></i> Home</a> <strong>Update Brand</strong></div>
  <h1>Update Brand</h1>
</div>
<div class="container-fluid">
  <hr>
  <div class="row-fluid">
    <div class="span12">
      <div class="widget-box">
        <div class="widget-title"> <span class="icon"> <i class="icon-align-justify"></i> </span>
          <h5>Update Brand</h5>
        </div>
        <div class="widget-content nopadding">
          <form method="post" class="form-horizontal" enctype="multipart/form-data">
           <?php
 $eid=$_GET['editid'];
$ret=mysqli_query($con,"select * from tblbrand where ID='$eid'");
$cnt=1;
while ($row=mysqli_fetch_array($ret)) {

?>
            <div class="control-group">
              <label class="control-label">Brand Name :</label>
              <div class="controls">
                <input type="text" class="span11" name="brandname" id="brandname" value="<?php  echo $row['BrandName'];?>" required='true' />
              </div>
            </div>
            
            <div class="control-group">
              <label class="control-label">Current Icon :</label>
              <div class="controls">
                <?php if (!empty($row['BrandIcon'])): ?>
                  <?php if (preg_match('/[\x{1F600}-\x{1F64F}]|[\x{1F300}-\x{1F5FF}]|[\x{1F680}-\x{1F6FF}]|[\x{1F1E0}-\x{1F1FF}]|[\x{2600}-\x{26FF}]|[\x{2700}-\x{27BF}]/u', $row['BrandIcon'])): ?>
                    <div style="font-size: 24px; margin: 5px 0;"><?php echo $row['BrandIcon']; ?></div>
                  <?php else: ?>
                    <img src="../<?php echo $row['BrandIcon']; ?>" style="max-width: 50px; max-height: 50px; border: 1px solid #ddd; padding: 5px; border-radius: 5px;" />
                  <?php endif; ?>
                <?php else: ?>
                  <span style="color: #999;">No icon set</span>
                <?php endif; ?>
              </div>
            </div>
            
            <div class="control-group">
              <label class="control-label">Brand Icon (Emoji) :</label>
              <div class="controls">
                <input type="text" class="span11" name="brandicon" id="brandicon" value="<?php echo preg_match('/[\x{1F600}-\x{1F64F}]|[\x{1F300}-\x{1F5FF}]|[\x{1F680}-\x{1F6FF}]|[\x{1F1E0}-\x{1F1FF}]|[\x{2600}-\x{26FF}]|[\x{2700}-\x{27BF}]/u', $row['BrandIcon']) ? $row['BrandIcon'] : '📱'; ?>" placeholder="Enter emoji icon (e.g., 📱, 🍎, 🔵)" />
                <span class="help-block">Enter an emoji icon for the brand</span>
              </div>
            </div>
            
            <div class="control-group">
              <label class="control-label">Upload New Icon Image :</label>
              <div class="controls">
                <input type="file" class="span11" name="icon_file" id="icon_file" accept="image/*" />
                <span class="help-block">Upload PNG, JPG, JPEG, GIF, or SVG image (optional - will use emoji if not provided)</span>
              </div>
            </div>
            
            <div class="control-group">
              <label class="control-label">Status :</label>
              <div class="controls">
                <?php  if($row['Status']=="1"){ ?>
                <input type="checkbox"  name="status" id="status" value="1"  checked="checked"/>
                <?php } else { ?>
                  <input type="checkbox" value='1' name="status" id="status" />
                  <?php } ?>
                <span class="help-block">Check to activate the brand</span>
              </div>
            </div>
            
           <?php } ?>
            <div class="form-actions">
              <button type="submit" class="btn btn-success" name="submit">Update</button>
            </div>
          </form>
        </div>
      </div>
    
    </div>
  </div>
 </div>
</div>
<?php include_once('includes/footer.php');?>
<?php include_once('includes/js.php');?>
</body>
</html>
<?php } ?>