-- ============================================================
-- ORDRE D'EXÉCUTION REQUIS :
--   1. Toutes les migrations Money+Xfer (schema.sql, v1.1 → v2.0)
--   2. migration_portail_client.sql  (crée client_accounts)
--   3. CE FICHIER : migration_v2.1_client_submissions.sql
-- ============================================================

-- ============================================================
-- Money+Xfer — Migration v2.1 — Soumissions Client
-- Flux : Client soumet → Agent taxe → Client paie + joint docs
--        → Agent valide → Client suit les étapes
-- Compatible MySQL 5.7+ / MariaDB 10.2+
-- ============================================================

USE akuxfer;

SET @db = DATABASE();

-- ============================================================
-- TABLE : client_transaction_requests
-- Demandes de transfert soumises par le client portail
-- L'agent les examine, applique la taxe, puis le client paie
-- ============================================================

CREATE TABLE IF NOT EXISTS client_transaction_requests (
    id                  INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    account_id          INT UNSIGNED NOT NULL,
    client_id           INT UNSIGNED DEFAULT NULL,    -- Lien KYC si existant
    reference           VARCHAR(100) DEFAULT NULL,    -- Réf Money+Xfer après validation
    transaction_id      INT UNSIGNED DEFAULT NULL,    -- Lié à transactions.id après validation

    -- Informations de transfert demandées par le client
    client_type         ENUM('particulier','entreprise') NOT NULL DEFAULT 'particulier',
    amount_sent         DECIMAL(15,2) NOT NULL,
    currency_from       VARCHAR(10)   NOT NULL DEFAULT 'XAF',
    currency_to         VARCHAR(10)   NOT NULL DEFAULT 'EUR',
    region              VARCHAR(60)   NOT NULL,
    destination         VARCHAR(120)  DEFAULT NULL,
    payment_method      ENUM('cash','depot_banque','virement','mobile_money','autre') NOT NULL DEFAULT 'cash',

    -- Bénéficiaire
    beneficiary_name    VARCHAR(160)  NOT NULL,
    beneficiary_phone   VARCHAR(40)   DEFAULT NULL,
    beneficiary_bank    VARCHAR(120)  DEFAULT NULL,
    beneficiary_iban    VARCHAR(42)   DEFAULT NULL,
    beneficiary_swift   VARCHAR(15)   DEFAULT NULL,
    notes               TEXT          DEFAULT NULL,

    -- Taxe appliquée par l'agent
    exchange_rate       DECIMAL(15,6) DEFAULT NULL,
    fee_pct             DECIMAL(6,3)  DEFAULT NULL,
    fee_amount          DECIMAL(15,2) DEFAULT NULL,
    amount_received     DECIMAL(15,2) DEFAULT NULL,
    agent_notes         TEXT          DEFAULT NULL,   -- Commentaire de l'agent au client
    taxed_by            INT UNSIGNED  DEFAULT NULL,   -- users.id de l'agent qui a taxé
    taxed_at            DATETIME      DEFAULT NULL,

    -- Documents joints par le client
    invoice_file        VARCHAR(255)  DEFAULT NULL,   -- Facture à payer
    proof_file          VARCHAR(255)  DEFAULT NULL,   -- Preuve de versement (bordereau, virement...)
    proof_type          ENUM('cash','depot_banque','virement','mobile_money','autre') DEFAULT NULL,
    docs_submitted_at   DATETIME      DEFAULT NULL,

    -- Statut du workflow
    status              ENUM(
        'en_attente',        -- Soumis par client, en attente de taxation par agent
        'taxe',              -- Agent a appliqué la taxe, client doit payer + joindre docs
        'docs_soumis',       -- Client a joint la facture + preuve, agent doit valider
        'valide',            -- Agent a validé, transaction créée dans Money+Xfer
        'rejete',            -- Agent a rejeté (docs invalides, montant erroné, etc.)
        'annule'             -- Annulé par le client
    ) NOT NULL DEFAULT 'en_attente',

    rejected_reason     TEXT          DEFAULT NULL,
    validated_by        INT UNSIGNED  DEFAULT NULL,   -- users.id de l'agent validateur
    validated_at        DATETIME      DEFAULT NULL,

    created_at          DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at          DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    FOREIGN KEY (account_id)  REFERENCES client_accounts(id)  ON DELETE CASCADE,
    FOREIGN KEY (client_id)   REFERENCES clients(id)          ON DELETE SET NULL,
    FOREIGN KEY (transaction_id) REFERENCES transactions(id)  ON DELETE SET NULL,
    FOREIGN KEY (taxed_by)    REFERENCES users(id)            ON DELETE SET NULL,
    FOREIGN KEY (validated_by) REFERENCES users(id)           ON DELETE SET NULL,

    INDEX idx_account(account_id),
    INDEX idx_status(status),
    INDEX idx_reference(reference),
    INDEX idx_created(created_at)
) ENGINE=InnoDB;

-- ============================================================
-- TABLE : client_request_logs
-- Journal d'activité sur chaque demande (audit trail)
-- ============================================================

CREATE TABLE IF NOT EXISTS client_request_logs (
    id          INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    request_id  INT UNSIGNED NOT NULL,
    actor_type  ENUM('client','agent','system') NOT NULL DEFAULT 'system',
    actor_id    INT UNSIGNED DEFAULT NULL,     -- account_id ou user_id selon actor_type
    old_status  VARCHAR(30)  DEFAULT NULL,
    new_status  VARCHAR(30)  NOT NULL,
    message     TEXT         DEFAULT NULL,
    created_at  DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY (request_id) REFERENCES client_transaction_requests(id) ON DELETE CASCADE,
    INDEX idx_request(request_id)
) ENGINE=InnoDB;

-- ============================================================
-- Permissions pour les agents
-- ============================================================

INSERT IGNORE INTO permissions (module, action, label) VALUES
('client_requests', 'view',     'Voir les demandes clients'),
('client_requests', 'tax',      'Appliquer la taxation sur une demande'),
('client_requests', 'validate', 'Valider/Rejeter une demande client'),
('client_requests', 'manage',   'Gestion complète des demandes clients');

-- Accès pour agents et managers
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id FROM roles r, permissions p
WHERE r.name IN ('super_admin','admin','manager','agent')
  AND p.module = 'client_requests'
  AND p.action IN ('view','tax','validate','manage');

-- ============================================================
-- Ajouter colonne uploads portail client (dossier dédié)
-- ============================================================

-- (Les fichiers sont stockés dans akuxfer/public/uploads/client_requests/)
-- Pas de migration SQL nécessaire pour le répertoire physique
