<?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 {
    $success_message = '';
    $error_message = '';
    
    if (isset($_POST['submit'])) {
        $brandname = trim($_POST['brandname']);
        $status = isset($_POST['status']) ? '1' : '0';
        $brandicon = trim($_POST['brandicon']);
        
        // Debug information
        echo "<script>console.log('Form Data - Brand: $brandname, Status: $status, Icon: $brandicon');</script>";
        
        if (empty($brandname)) {
            $error_message = "Brand name is required!";
        } else {
            // Create upload directory if it doesn't exist
            $upload_dir = 'images/brand_icons/';
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            // Handle file upload if provided
            $icon_path = $brandicon; // Default to emoji
            
            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)) {
                            $icon_path = 'admin/images/brand_icons/' . $new_file_name;
                            echo "<script>console.log('File uploaded successfully: $icon_path');</script>";
                        } else {
                            $error_message = "Failed to upload file!";
                        }
                    } else {
                        $error_message = "File size too large! Maximum 5MB allowed.";
                    }
                } else {
                    $error_message = "Invalid file type! Only PNG, JPG, JPEG, GIF, SVG allowed.";
                }
            }
            
            if (empty($error_message)) {
                // Insert into database
                $query = mysqli_query($con, "INSERT INTO tblbrand(BrandName, BrandIcon, Status) VALUES('$brandname', '$icon_path', '$status')");
                
                if ($query) {
                    $success_message = "Brand has been created successfully!";
                    echo "<script>alert('$success_message');</script>";
                    echo "<script>window.location.href = 'manage-brand.php';</script>";
                } else {
                    $error_message = "Database error: " . mysqli_error($con);
                    echo "<script>alert('$error_message');</script>";
                }
            } else {
                echo "<script>alert('$error_message');</script>";
            }
        }
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mobile Store Management System|| Add 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> <a href="add-brand.php" class="tip-bottom">Add Brand</a></div>
  <h1>Add 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>Add Brand</h5>
        </div>
        <div class="widget-content nopadding">
          <form method="post" class="form-horizontal" enctype="multipart/form-data">
           
            <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 isset($_POST['brandname']) ? $_POST['brandname'] : ''; ?>" required='true' />
              </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 isset($_POST['brandicon']) ? $_POST['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 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">
                <input type="checkbox" name="status" id="status" value="1" <?php echo (isset($_POST['status']) || !isset($_POST['submit'])) ? 'checked' : ''; ?> />
                <span class="help-block">Check to activate the brand</span>
              </div>
            </div>
            
            <div class="form-actions">
              <button type="submit" class="btn btn-success" name="submit">Add Brand</button>
              <a href="manage-brand.php" class="btn btn-default">Cancel</a>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
</div>
<?php include_once('includes/footer.php');?>
<?php include_once('includes/js.php');?>
</body>
</html>
<?php } ?>
