<?php require_once('header.php'); ?>

<?php
if (isset($_POST['form1'])) {

    $valid = 1;

    $path     = $_FILES['photo']['name'];
    $path_tmp = $_FILES['photo']['tmp_name'];

    // If new image selected
    if (!empty($path)) {

        $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
        $allowed_ext = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

        if (!in_array($ext, $allowed_ext)) {
            $valid = 0;
            $error_message = "Only JPG, JPEG, PNG, GIF & WEBP files are allowed.";
        }
    }

    if ($valid == 1) {

        // ❌ If no new image uploaded → only update caption
        if (empty($path)) {

            $statement = $pdo->prepare(
                "UPDATE tbl_photo SET caption=? WHERE id=?"
            );
            $statement->execute([
                $_POST['caption'],
                $_REQUEST['id']
            ]);

        } else {

            // ✅ Delete old image
            if (!empty($_POST['previous_photo']) &&
                file_exists('assets/images/gallery/' . $_POST['previous_photo'])) {

                unlink('assets/images/gallery/' . $_POST['previous_photo']);
            }

            // ✅ Generate UNIQUE image name (timestamp + uniqid)
            $unique_name = time() . '-' . uniqid();
            $final_name  = 'photo-' . $unique_name . '.' . $ext;

            // Upload new image
            move_uploaded_file(
                $path_tmp,
                'assets/images/gallery/' . $final_name
            );

            // Update DB with new image
            $statement = $pdo->prepare(
                "UPDATE tbl_photo SET caption=?, photo=? WHERE id=?"
            );
            $statement->execute([
                $_POST['caption'],
                $final_name,
                $_REQUEST['id']
            ]);
        }

        $success_message = 'Photo updated successfully.';
    }
}
?>


<?php
if(!isset($_REQUEST['id'])) {
	header('location: logout.php');
	exit;
} else {
	// Check the id is valid or not
	$statement = $pdo->prepare("SELECT * FROM tbl_photo WHERE id=?");
	$statement->execute(array($_REQUEST['id']));
	$total = $statement->rowCount();
	$result = $statement->fetchAll(PDO::FETCH_ASSOC);
	if( $total == 0 ) {
		header('location: logout.php');
		exit;
	}
}
?>

<section class="content-header">
	<div class="content-header-left">
		<h1>Edit Photo</h1>
	</div>
	<div class="content-header-right">
		<a href="photo.php" class="btn btn-primary btn-sm">View All</a>
	</div>
</section>

<?php							
foreach ($result as $row) {
	$caption = $row['caption'];
	$photo = $row['photo'];
}
?>

<section class="content">

	<div class="row">
		<div class="col-md-12">

			<?php if($error_message): ?>
			<div class="callout callout-danger">
			
			<p>
			<?php echo $error_message; ?>
			</p>
			</div>
			<?php endif; ?>

			<?php if($success_message): ?>
			<div class="callout callout-success">
			
			<p><?php echo $success_message; ?></p>
			</div>
			<?php endif; ?>

			<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">

				<div class="box box-info">
					<div class="box-body">
						<div class="form-group">
							<label for="" class="col-sm-2 control-label">Photo Caption <span>*</span></label>
							
							 
							<div class="col-sm-3">
								<select class="form-control" name="caption">
                                    <option value="Image">Image</option>
                                    <option value="Video">Video</option>    
                                </select>
								
								
							
							</div>
						</div>
						<div class="form-group">
				            <label for="" class="col-sm-2 control-label">Existing Photo</label>
				            <div class="col-sm-6" style="padding-top:6px;">
				                <img src="assets/images/gallery/<?php echo $photo; ?>" class="existing-photo" style="width:300px;">

				                <input type="hidden" name="previous_photo" value="<?php echo $photo; ?>">
				            </div>
				        </div>
						<div class="form-group">
							<label for="" class="col-sm-2 control-label">Upload New Photo <span>*</span></label>
							<div class="col-sm-4" style="padding-top:6px;">
								<input type="file" name="photo">
							</div>
						</div>
						<div class="form-group">
							<label for="" class="col-sm-2 control-label"></label>
							<div class="col-sm-6">
								<button type="submit" class="btn btn-success pull-left" name="form1">Submit</button>
							</div>
						</div>
					</div>
				</div>
			</form>
		</div>
	</div>
</section>

<?php require_once('footer.php'); ?>