-- ============================================================================
-- CT NAILS — Migration 004: PayHere + Membership & Loyalty (Phase 6)
-- Import:
--   mysql -u <user> -p <database> < database/migrations/004_payhere_loyalty.sql
--
-- Only what is genuinely missing is added here. Everything else
-- already exists in schema.sql:
--   * payments.payhere_order_id / payhere_payment_id — already in schema.
--   * appointments.deposit_amount / discount_amount / coupon_code — already in schema.
--   * appointments.payment_status ('unpaid','deposit_paid','paid','refunded') — already in schema.
--   * loyalty_points (user ledger) / customer_memberships — already in schema.
--   * settings.booking_deposit_percent / points_per_rupee — already in seed.
--
-- What this migration adds:
--   * payments.status_code — PayHere status code (2 = success, 0 = pending,
--     -1 = cancelled, -2 = failed, -3 = chargeback) for the receipt view.
--   * payments.refund_reason — admin-recorded reason when a payment is
--     flagged refunded (the money itself is refunded in the PayHere
--     merchant dashboard — PayHere has no merchant refund API).
--   * appointments.amount_paid — how much has actually been paid so far
--     (deposit or full), so the remaining balance can be shown and paid.
--   * appointments.points_redeemed / points_earned — audit trail on the
--     booking itself (the ledgers stay the source of truth).
--   * memberships.min_spend — lifetime-spend threshold for automatic
--     tier upgrades (Silver LKR 0, Gold LKR 25,000, Platinum LKR 60,000).
--   * guest_loyalty + guest_loyalty_log — guests have no `users` row
--     (Phase 3 portal is deferred), so loyalty for guests is keyed by
--     their normalised phone number, mirroring users/loyalty_points.
--   * payhere_notifications — every PayHere notify callback is logged
--     here (hash valid or not), so a failed or duplicate callback can
--     be investigated and an invalid-hash attempt is on record.
--   * settings rows: points_value (LKR value of 1 point), notification
--     toggles for payment / reschedule emails.
-- ============================================================================

ALTER TABLE `payments`
  ADD COLUMN `status_code` VARCHAR(10) NULL DEFAULT NULL AFTER `payhere_payment_id`,
  ADD COLUMN `refund_reason` VARCHAR(255) NULL DEFAULT NULL AFTER `notes`;

ALTER TABLE `appointments`
  ADD COLUMN `amount_paid` DECIMAL(10,2) NOT NULL DEFAULT 0.00 AFTER `deposit_amount`,
  ADD COLUMN `points_redeemed` INT NOT NULL DEFAULT 0 AFTER `discount_amount`,
  ADD COLUMN `points_earned` INT NOT NULL DEFAULT 0 AFTER `points_redeemed`;

ALTER TABLE `memberships`
  ADD COLUMN `min_spend` DECIMAL(10,2) NOT NULL DEFAULT 0.00 AFTER `points_multiplier`;

UPDATE `memberships` SET `min_spend` = 0.00 WHERE `tier` = 'silver';
UPDATE `memberships` SET `min_spend` = 25000.00 WHERE `tier` = 'gold';
UPDATE `memberships` SET `min_spend` = 60000.00 WHERE `tier` = 'platinum';

-- ----------------------------------------------------------------------------
-- Guest loyalty — keyed by normalised phone (07XXXXXXXX), because guest
-- bookings have no users row. Mirrors users.points_balance +
-- loyalty_points (ledger) for registered customers.
-- ----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `guest_loyalty` (
  `phone`          VARCHAR(20)     NOT NULL COMMENT 'Normalised Sri Lankan mobile, 07XXXXXXXX',
  `points_balance` INT             NOT NULL DEFAULT 0,
  `lifetime_spend` DECIMAL(10,2)  NOT NULL DEFAULT 0.00 COMMENT 'Total paid amount, used for tier upgrades',
  `tier`           ENUM('none','silver','gold','platinum') NOT NULL DEFAULT 'none',
  `customer_name`  VARCHAR(100)    NULL DEFAULT NULL,
  `updated_at`     TIMESTAMP       NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`phone`),
  INDEX `idx_guestloyalty_tier` (`tier`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Loyalty balances + tiers for guest customers, keyed by phone';

CREATE TABLE IF NOT EXISTS `guest_loyalty_log` (
  `id`               BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `phone`            VARCHAR(20)     NOT NULL,
  `appointment_id`   BIGINT UNSIGNED NULL DEFAULT NULL,
  `points`           INT             NOT NULL COMMENT 'Positive = earned, negative = redeemed/adjusted down',
  `transaction_type` ENUM('earn','redeem','adjust','birthday') NOT NULL DEFAULT 'earn',
  `balance_after`    INT             NOT NULL DEFAULT 0,
  `description`      VARCHAR(255)    NULL DEFAULT NULL,
  `created_at`       TIMESTAMP       NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  INDEX `idx_guestlog_phone` (`phone`),
  INDEX `idx_guestlog_appt` (`appointment_id`),
  CONSTRAINT `fk_guestlog_appt`
    FOREIGN KEY (`appointment_id`) REFERENCES `appointments` (`id`)
    ON UPDATE CASCADE ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Append-only points ledger for guests (mirrors loyalty_points)';

-- ----------------------------------------------------------------------------
-- PayHere notify log — every callback, valid or not, is recorded.
-- ----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `payhere_notifications` (
  `id`              BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `order_id`        VARCHAR(100)    NULL DEFAULT NULL COMMENT 'Booking reference (CT-...)',
  `payment_id`      VARCHAR(100)    NULL DEFAULT NULL COMMENT 'PayHere payment id',
  `status_code`     VARCHAR(10)     NULL DEFAULT NULL,
  `amount`          DECIMAL(10,2)   NULL DEFAULT NULL,
  `currency`        CHAR(3)         NULL DEFAULT NULL,
  `hash_valid`      TINYINT(1)      NOT NULL DEFAULT 0,
  `processed`       TINYINT(1)      NOT NULL DEFAULT 0 COMMENT '1 = this callback changed a payment',
  `raw_payload`     TEXT            NULL DEFAULT NULL COMMENT 'JSON of the POST fields (no secrets)',
  `created_at`      TIMESTAMP       NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  INDEX `idx_phnotif_order` (`order_id`),
  INDEX `idx_phnotif_created` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Audit log of PayHere notify callbacks';

-- ----------------------------------------------------------------------------
-- New settings (safe to re-run)
-- ----------------------------------------------------------------------------
INSERT INTO `settings` (`setting_key`, `setting_value`, `description`) VALUES
('points_value', '1', 'LKR value of 1 loyalty point when redeeming (1 point = LKR 1)'),
('notify_payment_email', '1', 'Email the studio when an online payment is received'),
('notify_reschedule_email', '1', 'Email the studio when a booking is rescheduled or cancelled')
ON DUPLICATE KEY UPDATE `setting_value` = VALUES(`setting_value`);
