<?php 
// 1. Protocol & Host Detection (Proxy Aware for Heroku)
$is_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https')
    || (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off')
    || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443);
$protocol = $is_https ? "https" : "http";

$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'loveweddingcam.com';

// Fix script directory path (handling Windows backslashes)
$script_dir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
$site_base = rtrim($protocol . "://" . $host . $script_dir, '/') . '/';
$domain_root = $protocol . "://" . $host . "/";

$current_full_url = $protocol . "://" . $host . $_SERVER['REQUEST_URI'];

$og_title = "Love Wedding - Wedding Services in Cambodia";
$og_desc = "Love Wedding, Wedding in Cambodia, Wedding Services, Dresses, Accessories and Photo Gallery";
$og_url = $current_full_url;

$p_val = isset($_GET['p']) ? $_GET['p'] : (isset($p) ? $p : '');
$s_id = isset($_GET['s_id']) ? $_GET['s_id'] : (isset($_GET['id']) ? $_GET['id'] : '');
$id_detail = isset($_GET['id_detail']) ? $_GET['id_detail'] : (isset($_GET['id']) ? $_GET['id'] : '');
$a_id = isset($_GET['a_id']) ? $_GET['a_id'] : (isset($_GET['id']) ? $_GET['id'] : '');
$b_id = isset($_GET['b_id']) ? $_GET['b_id'] : (isset($_GET['id']) ? $_GET['id'] : '');

$site_root_dir = dirname(__DIR__); // Physical path to /Site directory
$project_root_dir = dirname($site_root_dir); // Physical path to project root

// Helper: Extract first <img> tag src from HTML
function extract_first_image_src($html) {
	if (empty($html)) return false;
	if (preg_match('/<img[^>]+src=["\']([^"\']+)["\']/i', $html, $matches)) {
		$src = trim($matches[1]);
		// Clean leading ../ or ./
		$src = preg_replace('/^(\.\.\/|\.\/)+/', '', $src);
		return $src;
	}
	return false;
}

// Helper: Resolve local path and public absolute URL for any candidate image path
function resolve_image_paths($src, $site_root_dir, $project_root_dir, $site_base, $domain_root) {
	if (empty($src)) return false;
	$clean_src = preg_replace('/^(\.\.\/|\.\/)+/', '', trim($src));

	// 1. Check project root
	$proj_path = $project_root_dir . "/" . $clean_src;
	if (file_exists($proj_path) && !is_dir($proj_path)) {
		return array(
			'local'  => $proj_path,
			'public' => $domain_root . $clean_src
		);
	}

	// 2. Check site root (/Site/)
	$site_path = $site_root_dir . "/" . $clean_src;
	if (file_exists($site_path) && !is_dir($site_path)) {
		return array(
			'local'  => $site_path,
			'public' => $site_base . $clean_src
		);
	}

	// 3. Check inside /Site/images/ if src starts with images/
	if (strpos($clean_src, 'images/') === 0) {
		$site_img_path = $site_root_dir . "/" . $clean_src;
		if (file_exists($site_img_path) && !is_dir($site_img_path)) {
			return array(
				'local'  => $site_img_path,
				'public' => $site_base . $clean_src
			);
		}
	}

	// Fallback
	if (strpos($clean_src, 'uploads/') === 0) {
		return array(
			'local'  => $project_root_dir . "/" . $clean_src,
			'public' => $domain_root . $clean_src
		);
	}

	return array(
		'local'  => $site_root_dir . "/" . $clean_src,
		'public' => $site_base . $clean_src
	);
}

$resolved = false;

if ($p_val == 'clothes' && !empty($id_detail)) {
	$res = mysql_query("SELECT * FROM tbl_clothes WHERE id='".mysql_real_escape_string($id_detail)."'");
	if ($res && $r = mysql_fetch_array($res)) {
		$og_title = !empty($r['code_id']) ? "Love Wedding - " . $r['code_id'] : (isset($r['name']) && !empty($r['name']) ? $r['name'] : "Love Wedding Clothes");
		if (!empty($r['detail'])) {
			$og_desc = mb_substr(trim(strip_tags($r['detail'])), 0, 200, 'utf-8');
		}

		// First try extracted image from detail HTML
		$extracted_src = extract_first_image_src($r['detail']);
		if ($extracted_src) {
			$resolved = resolve_image_paths($extracted_src, $site_root_dir, $project_root_dir, $site_base, $domain_root);
		}

		// Fallback to image field
		if (!$resolved && !empty($r['image'])) {
			$img_name = $r['image'];
			if (file_exists($site_root_dir . "/images/clothes/b/" . $img_name)) {
				$resolved = array(
					'local'  => $site_root_dir . "/images/clothes/b/" . $img_name,
					'public' => $site_base . "images/clothes/b/" . rawurlencode($img_name)
				);
			} else if (file_exists($site_root_dir . "/images/clothes/" . $img_name)) {
				$resolved = array(
					'local'  => $site_root_dir . "/images/clothes/" . $img_name,
					'public' => $site_base . "images/clothes/" . rawurlencode($img_name)
				);
			}
		}
	}
} else if ($p_val == 'service' && !empty($s_id)) {
	$res = mysql_query("SELECT * FROM tbl_service WHERE id='".mysql_real_escape_string($s_id)."'");
	if ($res && $r = mysql_fetch_array($res)) {
		if (!empty($r['name'])) {
			$og_title = "Love Wedding - " . $r['name'];
		}
		if (!empty($r['detail'])) {
			$og_desc = mb_substr(trim(strip_tags($r['detail'])), 0, 200, 'utf-8');
		} else if (!empty($r['description'])) {
			$og_desc = mb_substr(trim(strip_tags($r['description'])), 0, 200, 'utf-8');
		}

		// Get image first from detail or description HTML
		$extracted_src = extract_first_image_src(!empty($r['detail']) ? $r['detail'] : $r['description']);
		if ($extracted_src) {
			$resolved = resolve_image_paths($extracted_src, $site_root_dir, $project_root_dir, $site_base, $domain_root);
		}

		// Fallback to image field
		if (!$resolved && !empty($r['image'])) {
			$img_name = $r['image'];
			$resolved = resolve_image_paths("images/service/" . $img_name, $site_root_dir, $project_root_dir, $site_base, $domain_root);
		}
	}
} else if ($p_val == 'all' && !empty($a_id)) {
	$res = mysql_query("SELECT * FROM tbl_all WHERE id='".mysql_real_escape_string($a_id)."'");
	if ($res && $r = mysql_fetch_array($res)) {
		if (!empty($r['title'])) {
			$og_title = "Love Wedding - " . $r['title'];
		}
		if (!empty($r['detail'])) {
			$og_desc = mb_substr(trim(strip_tags($r['detail'])), 0, 200, 'utf-8');
		}

		$extracted_src = extract_first_image_src($r['detail']);
		if ($extracted_src) {
			$resolved = resolve_image_paths($extracted_src, $site_root_dir, $project_root_dir, $site_base, $domain_root);
		}

		if (!$resolved && !empty($r['image'])) {
			$img_name = $r['image'];
			$resolved = resolve_image_paths("images/all/" . $img_name, $site_root_dir, $project_root_dir, $site_base, $domain_root);
		}
	}
} else if ($p_val == 'beauty_women' && !empty($b_id)) {
	$res = mysql_query("SELECT * FROM tbl_beauty WHERE id='".mysql_real_escape_string($b_id)."'");
	if ($res && $r = mysql_fetch_array($res)) {
		if (!empty($r['title'])) {
			$og_title = "Love Wedding - " . $r['title'];
		}
		if (!empty($r['detail'])) {
			$og_desc = mb_substr(trim(strip_tags($r['detail'])), 0, 200, 'utf-8');
		}

		$extracted_src = extract_first_image_src($r['detail']);
		if ($extracted_src) {
			$resolved = resolve_image_paths($extracted_src, $site_root_dir, $project_root_dir, $site_base, $domain_root);
		}

		if (!$resolved && !empty($r['image'])) {
			$img_name = $r['image'];
			$resolved = resolve_image_paths("images/beauty/" . $img_name, $site_root_dir, $project_root_dir, $site_base, $domain_root);
		}
	}
}

// Fallback to header logo if no specific item image resolved
if (!$resolved) {
	$q_logo = mysql_query("SELECT image FROM tbllogo WHERE status=1 ORDER BY id DESC LIMIT 1");
	if ($q_logo && $r_logo = mysql_fetch_array($q_logo)) {
		if (!empty($r_logo['image'])) {
			$resolved = resolve_image_paths("images/" . $r_logo['image'], $site_root_dir, $project_root_dir, $site_base, $domain_root);
		}
	}
}

if (!$resolved) {
	$resolved = resolve_image_paths("images/logo.png", $site_root_dir, $project_root_dir, $site_base, $domain_root);
}

$local_img_path = $resolved['local'];
$raw_rel_path = str_replace(array($project_root_dir . '/', $site_root_dir . '/'), '', $local_img_path);
$og_image = $site_base . "og_banner.php?img=" . rawurlencode($raw_rel_path);

// Dynamic Image Dimension & Type Extraction
$og_img_width = 1200;
$og_img_height = 630;
$og_img_mime = 'image/jpeg';

// Ensure width & height hint for Facebook to display Large Full Banner Preview Above Text (1200x630, 1.91:1 ratio)
$og_width_hint = 1200;
$og_height_hint = 630;

$og_title_clean = htmlspecialchars($og_title, ENT_QUOTES, 'UTF-8');
$og_desc_clean = htmlspecialchars(preg_replace('/\s+/', ' ', $og_desc), ENT_QUOTES, 'UTF-8');
?>
<title><?php echo $og_title_clean; ?></title>
<!-- Open Graph / Facebook Sharing Meta Tags -->
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Love Wedding" />
<meta property="og:title" content="<?php echo $og_title_clean; ?>" />
<meta property="og:description" content="<?php echo $og_desc_clean; ?>" />
<meta property="og:image" content="<?php echo $og_image; ?>" />
<meta property="og:image:secure_url" content="<?php echo $og_image; ?>" />
<?php if (!empty($og_img_mime)): ?>
<meta property="og:image:type" content="<?php echo $og_img_mime; ?>" />
<?php endif; ?>
<meta property="og:image:width" content="<?php echo $og_width_hint; ?>" />
<meta property="og:image:height" content="<?php echo $og_height_hint; ?>" />
<meta property="og:url" content="<?php echo htmlspecialchars($og_url, ENT_QUOTES, 'UTF-8'); ?>" />

<!-- Twitter Card Meta Tags -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="<?php echo $og_title_clean; ?>" />
<meta name="twitter:description" content="<?php echo $og_desc_clean; ?>" />
<meta name="twitter:image" content="<?php echo $og_image; ?>" />

<link rel="image_src" href="<?php echo $og_image; ?>"/>
<link rel="canonical" href="<?php echo htmlspecialchars($og_url, ENT_QUOTES, 'UTF-8'); ?>" />
<meta name="description" content="<?php echo $og_desc_clean; ?>" />