#!/usr/bin/env bash

# Checkout reminder cron job
# Run hourly to send abandoned checkout reminders

set -euo pipefail

APP_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$APP_DIR"

LOG_DIR="$APP_DIR/storage/logs"
mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/cron-checkout-reminders.log"
LOCK_FILE="$LOG_DIR/checkout_reminders.lock"

exec 204>"$LOCK_FILE"
if ! flock -n 204; then
    exit 0
fi

timestamp() {
    date --iso-8601=seconds
}

echo "[$(timestamp)] Running checkout:send-reminders" >> "$LOG_FILE"
if /usr/bin/env php artisan checkout:send-reminders --no-interaction --quiet >> "$LOG_FILE" 2>&1; then
    echo "[$(timestamp)] checkout:send-reminders completed" >> "$LOG_FILE"
else
    status=$?
    echo "[$(timestamp)] checkout:send-reminders failed (exit $status)" >> "$LOG_FILE"
    exit $status
fi
