<?php 

session_start();
if (isset($_SESSION['user_email'])){

require '../../config.php';
require '../functions.php';

$connect = connect($database);

$check_access = check_access($connect);

if ($check_access['user_role'] == 1 || $check_access['user_role'] == 2){

if ($_SERVER['REQUEST_METHOD'] == 'POST'){

			$store_title = cleardata($_POST['store_title']);
			$store_seotitle = cleardata($_POST['store_seotitle']);
			$store_description = cleardata($_POST['store_description']);
			$store_seodescription = cleardata($_POST['store_seodescription']);
			$store_featured = cleardata($_POST['store_featured']);
			
			// Handle parent and subcategory selection
			$parent_category = !empty($_POST['parent_category']) ? cleardata($_POST['parent_category']) : NULL;
			$subcategory = !empty($_POST['subcategory']) ? cleardata($_POST['subcategory']) : NULL;
			
			// Build category array - if subcategory selected, include both parent and sub
			$store_categories = array();
			if ($parent_category) {
				$store_categories[] = $parent_category;
			}
			if ($subcategory && $subcategory != $parent_category) {
				// Only add subcategory if it's different from parent (avoid duplicates)
				$store_categories[] = $subcategory;
			}
			
			// Remove duplicates just in case
			$store_categories = array_unique($store_categories);
			
			// Keep first category for backward compatibility
			$store_category = !empty($store_categories) ? $store_categories[0] : NULL;
			$converted_slug = convertSlug(cleardata($_POST['store_title']));
			
			// Auto-generate SEO title if empty
			if (empty($store_seotitle)) {
				$store_seotitle = $store_title . " Coupons, Deals & Cashback Offers | Alonedeals";
			}
			
			// Auto-generate SEO description if empty
			if (empty($store_seodescription)) {
				$store_seodescription = "Get the latest " . $store_title . " coupons, promo codes & exclusive cashback offers on Alonedeals. Save more on every purchase today!";
			}
			
			// Auto-generate store description if empty
			if (empty($store_description)) {
				// Get category name for better description
				$category_name = '';
				$product_type = 'products';
				
				if ($subcategory) {
					$cat_query = $connect->prepare("SELECT subcategory_title FROM subcategories WHERE subcategory_id = :id");
					$cat_query->execute([':id' => $subcategory]);
					$cat_result = $cat_query->fetch(PDO::FETCH_ASSOC);
					if ($cat_result) {
						$category_name = $cat_result['subcategory_title'];
						$product_type = strtolower($category_name);
					}
				} elseif ($parent_category) {
					$cat_query = $connect->prepare("SELECT category_title FROM categories WHERE category_id = :id");
					$cat_query->execute([':id' => $parent_category]);
					$cat_result = $cat_query->fetch(PDO::FETCH_ASSOC);
					if ($cat_result) {
						$category_name = $cat_result['category_title'];
						$product_type = strtolower($category_name);
					}
				}
				
				// Generate description with dynamic content
				$store_description = "At Alonedeals, you can find the latest " . $store_title . " coupon codes, deals, and cashback offers to help you save more on every purchase. Whether you're shopping for " . $product_type . " or daily essentials, our verified deals ensure maximum savings.";
			}
			
			$exists = get_store_slug($connect, $converted_slug);

			if ($exists > 0)
			{
				$new_number = $exists + 1;
				$slug = $converted_slug."-".$new_number;

			}else{

				$slug = $converted_slug;
			}

			$extsAllowed = array('jpg', 'jpeg', 'png', 'gif', 'webp', 'avif');
			$store_image = 'default-store.png'; // Default image
			$image_type = isset($_POST['image_type']) ? $_POST['image_type'] : 'upload';
			
			// Initialize CDN fields
			$store_image_cdn_url = '';
			$store_use_cdn = 0;

			// Handle Image URL - Just save the URL, don't download
			if ($image_type == 'url' && !empty($_POST['image_url'])) {
				$image_url = trim($_POST['image_url']);
				
				// Validate URL
				if (filter_var($image_url, FILTER_VALIDATE_URL)) {
					$store_image_cdn_url = $image_url;
					$store_use_cdn = 1;
					// Keep default image for local field
					$store_image = 'default-store.png';
				}
			}
			// Handle File Upload
			else if (isset($_FILES['store_image']) && $_FILES['store_image']['error'] == 0) {
				$extUpload = strtolower(substr(strrchr($_FILES['store_image']['name'], '.') ,1));
		
				if (in_array($extUpload, $extsAllowed) ) { 
		
					$image = $_FILES['store_image']['tmp_name'];
					$imagefile = explode(".", $_FILES["store_image"]["name"]);
					$renamefile = round(microtime(true)) . '.' . end($imagefile);
					$image_upload = '../../images/';
					move_uploaded_file($image, $image_upload . 'store_' . $renamefile);
					$store_image = 'store_' . $renamefile;
				}
			}

			$statment = $connect->prepare("INSERT INTO stores (store_id, store_title, store_seotitle, store_description, store_seodescription, store_featured, store_category, store_slug, store_image, store_image_cdn_url, store_use_cdn) VALUES (null, :store_title, :store_seotitle, :store_description, :store_seodescription, :store_featured, :store_category, :store_slug, :store_image, :store_image_cdn_url, :store_use_cdn)");

			$statment->execute(array(
				':store_title' => $store_title,
				':store_slug' => $slug,
				':store_seotitle' => $store_seotitle,
				':store_description' => $store_description,
				':store_seodescription' => $store_seodescription,
				':store_featured' => $store_featured,
				':store_category' => $store_category,
				':store_image' => $store_image,
				':store_image_cdn_url' => $store_image_cdn_url,
				':store_use_cdn' => $store_use_cdn
			));

			// Get the newly inserted store ID
			$new_store_id = $connect->lastInsertId();
			
			// Insert category associations (parent and/or subcategory)
			if (!empty($store_categories)) {
				$insert_cat_stmt = $connect->prepare("INSERT INTO store_categories (store_id, category_id) VALUES (:store_id, :category_id)");
				foreach ($store_categories as $category_id) {
					$insert_cat_stmt->execute(array(
						':store_id' => $new_store_id,
						':category_id' => $category_id
					));
				}
			}

			header('Location: ./stores.php');

}
$categories = get_all_categories($connect);

// Get all subcategories
$subcategories_query = $connect->query("SELECT * FROM subcategories WHERE subcategory_status = 1 ORDER BY subcategory_title");
$all_subcategories = $subcategories_query->fetchAll(PDO::FETCH_ASSOC);

require '../views/header.view.php';
require '../views/new.store.view.php';

}else{
	
	header('Location:'.SITE_URL);
}

	require '../views/footer.view.php';

}else {

	header('Location: ./login.php');	

}


?>