<?php
$dirName = '/opt/kumakumakumabear/secret/cd';

//※枚数は日数から自動計算(例:9/1～9/3で2枚)
$startDay = '2023-3-23';	//カウントダウン開始日
$endDay   = '2023-4-3';	//0になる日

function diffday($startDay, $endDay) {
	$startTime = strtotime($startDay);
	$endTime   = strtotime($endDay);
	$tmp = $startTime;
	$cnt = 0;
	while($tmp < $endTime) {
		$tmp = strtotime('+1 day', $tmp);
		$cnt++;
	}

	return $cnt;
}


if(time() < strtotime($startDay)) {
	$imgNo = diffday($startDay, $endDay);
} else if(time() >= strtotime($endDay)) {
	$imgNo = 0;
} else {
	$imgNo = diffday(date('Y-m-d'), $endDay);
}

$extList = array('jpg', 'jpeg', 'png', 'gif');
$filePath = null;
$fileInfo = null;
foreach($extList as $ext) {
	$filePath = $dirName.sprintf('%02d', $imgNo).'.'.$ext;

	if(is_file($filePath)) {
		$fileInfo = pathinfo($filePath);
		break;
	}
}

if(is_null($filePath) || !is_file($filePath)) {
	header('HTTP/1.0 404 Not Found');
	exit();
}

switch(strtolower($fileInfo['extension'])) {
	case 'jpg';
	case 'jpeg':
		$contentType = 'image/jpeg';
		break;
	case 'gif':
		$contentType = 'image/gif';
		break;
	case 'png':
		$contentType = 'image/png';
		break;
	default:
		$contentType = 'application/octet-stream';
		break;
}

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Content-type: {$contentType}");
header("Content-Disposition: inline; filename={$fileInfo['basename']}");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '.filesize($filePath));
header("Last-Modified: ".date('r'));
header('Connection: close');
ob_end_clean();
readfile($filePath);
exit();
?>