<?php
require_once __DIR__ . '/header.php';

$error_message = '';
$success_message = '';

if (!isset($_REQUEST['id']) || !is_numeric($_REQUEST['id'])) {
    header('location: photo.php');
    exit;
}

$id = (int)$_REQUEST['id'];

$statement = $pdo->prepare("SELECT * FROM tbl_photo WHERE id=?");
$statement->execute([$id]);
$row = $statement->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    header('location: photo.php');
    exit;
}

$caption = $row['caption'];
$photo = $row['photo'];

if (isset($_POST['form1'])) {

    $new_caption = trim($_POST['caption'] ?? '');

    if ($new_caption === '') {
        $error_message = 'Photo Caption can not be empty.';
    } else {

        $file_error = $_FILES['photo']['error'] ?? UPLOAD_ERR_NO_FILE;
        $path = $_FILES['photo']['name'] ?? '';
        $path_tmp = $_FILES['photo']['tmp_name'] ?? '';

        if ($file_error === UPLOAD_ERR_NO_FILE) {

            $statement = $pdo->prepare(
                "UPDATE tbl_photo SET caption=? WHERE id=?"
            );

            $statement->execute([
                $new_caption,
                $id
            ]);

            $caption = $new_caption;

            $success_message = 'Photo is updated successfully.';

        } elseif ($file_error === UPLOAD_ERR_OK) {

            $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));

            $allowed_extensions = [
                'jpg',
                'jpeg',
                'png',
                'gif',
                'webp'
            ];

            if (!in_array($ext, $allowed_extensions, true)) {

                $error_message = 'Please upload JPG, JPEG, PNG, GIF or WEBP file.';

            } else {

                $upload_dir = dirname(__DIR__) . '/assets/images/gallery/';

                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0755, true);
                }

                $final_name = 'photo-' . time() . '.' . $ext;
                $upload_path = $upload_dir . $final_name;

                if (move_uploaded_file($path_tmp, $upload_path)) {

                    $old_photo_path = $upload_dir . $photo;

                    if (
                        !empty($photo) &&
                        $photo !== $final_name &&
                        file_exists($old_photo_path)
                    ) {
                        unlink($old_photo_path);
                    }

                    $statement = $pdo->prepare(
                        "UPDATE tbl_photo SET caption=?, photo=? WHERE id=?"
                    );

                    $statement->execute([
                        $new_caption,
                        $final_name,
                        $id
                    ]);

                    $caption = $new_caption;
                    $photo = $final_name;

                    $success_message = 'Photo is updated successfully.';

                } else {

                    $error_message = 'Photo upload failed. Please check the gallery folder.';
                }
            }

        } else {

            $error_message = 'There was a problem uploading the photo.';
        }
    }
}
?>

<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>

<section class="content">

    <div class="row">

        <div class="col-md-12">

            <?php if (!empty($error_message)): ?>

                <div class="callout callout-danger">
                    <p>
                        <?= htmlspecialchars(
                            $error_message,
                            ENT_QUOTES,
                            'UTF-8'
                        ) ?>
                    </p>
                </div>

            <?php endif; ?>

            <?php if (!empty($success_message)): ?>

                <div class="callout callout-success">
                    <p>
                        <?= htmlspecialchars(
                            $success_message,
                            ENT_QUOTES,
                            'UTF-8'
                        ) ?>
                    </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 class="col-sm-2 control-label">
                                Photo Caption <span>*</span>
                            </label>

                            <div class="col-sm-4">

                                <input
                                    type="text"
                                    class="form-control"
                                    name="caption"
                                    value="<?= htmlspecialchars(
                                        $caption,
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>"
                                    required>

                            </div>

                        </div>

                        <div class="form-group">

                            <label class="col-sm-2 control-label">
                                Existing Photo
                            </label>

                            <div class="col-sm-6" style="padding-top:6px;">

                                <img
                                    src="../assets/images/gallery/<?= htmlspecialchars(
                                        $photo,
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>"
                                    alt="<?= htmlspecialchars(
                                        $caption,
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>"
                                    class="existing-photo"
                                    style="width:300px;max-width:100%;height:auto;display:block;border-radius:6px;">

                                <input
                                    type="hidden"
                                    name="previous_photo"
                                    value="<?= htmlspecialchars(
                                        $photo,
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>">

                            </div>

                        </div>

                        <div class="form-group">

                            <label class="col-sm-2 control-label">
                                Upload New Photo
                            </label>

                            <div class="col-sm-4" style="padding-top:6px;">

                                <input
                                    type="file"
                                    name="photo"
                                    accept=".jpg,.jpeg,.png,.gif,.webp">

                                <p style="margin-top:7px;color:#777;">
                                    Leave empty if you only want to update the caption.
                                </p>

                            </div>

                        </div>

                        <div class="form-group">

                            <label class="col-sm-2 control-label"></label>

                            <div class="col-sm-6">

                                <button
                                    type="submit"
                                    class="btn btn-success pull-left"
                                    name="form1">
                                    Update
                                </button>

                            </div>

                        </div>

                    </div>

                </div>

            </form>

        </div>

    </div>

</section>

<?php require_once __DIR__ . '/footer.php'; ?>