<?php
include 'branch_connection.php';
require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

/* ===============================
   INPUTS
================================ */
$proposal_id = intval($_POST['proposal_id'] ?? 0);
$user_id     = intval($_POST['user_id'] ?? 0);
$token       = trim($_POST['token'] ?? '');

if (!$proposal_id) {
    exit("Invalid request");
}

/* ===============================
   FETCH CURRENT STATUS
================================ */
$res = mysqli_query($conn, "SELECT status FROM proposals WHERE id='$proposal_id'");
if (!$res || mysqli_num_rows($res) == 0) {
    exit("Proposal not found");
}

$row = mysqli_fetch_assoc($res);

/* ===============================
   IF ALREADY APPROVED
================================ */
if ($row['status'] === 'Approved') {
    exit("This proposal is already approved");
}

/* ==================================================
   TOKEN EXISTS → JUST UPDATE STATUS
================================================== */
if ($token !== '') {
    $chk = mysqli_query($conn,
        "SELECT id FROM proposals 
         WHERE id='$proposal_id' AND approval_token='$token'"
    );

    if (!$chk || mysqli_num_rows($chk) == 0) {
        exit("Invalid or expired approval link");
    }

    mysqli_query($conn,
        "UPDATE proposals 
         SET status='Approved',
             approved_at=NOW(),
             send_approval_date=NOW()
         WHERE id='$proposal_id'"
    );

    exit("Proposal approved successfully via token!");
}

/* ==================================================
   NO TOKEN → EMAIL FLOW
================================================== */
if (!$user_id) {
    exit("Invalid request");
}

/* 1️⃣ Fetch selected user */
$user_res = mysqli_query($conn, "SELECT email, name FROM users WHERE id='$user_id'");
if (!$user_res || mysqli_num_rows($user_res) == 0) {
    exit("User not found");
}
$user = mysqli_fetch_assoc($user_res);

/* 2️⃣ Generate token */
$token = bin2hex(random_bytes(32));

/* 3️⃣ Update proposal */
mysqli_query($conn, "
    UPDATE proposals 
    SET approved_by='$user_id',
        approval_token='$token',
        send_approval_date=NOW()
    WHERE id='$proposal_id'
");

/* 4️⃣ Proposal link */
$proposal_link = "https://xtodo.programersapps.com/systemsoft/leadsnew/test.php?orderid=$proposal_id&token=$token";

/* 5️⃣ Send Email */
$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'bharathmarriage314@gmail.com';
    $mail->Password   = 'xakw oceb pzkx hngk';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    $mail->setFrom('programers680@gmail.com', 'Proposal System');
    $mail->addAddress($user['email'], $user['name']);

    $mail->isHTML(true);
    $mail->Subject = 'Proposal Approved – Action Required';
    $mail->Body = "
        <p>Dear <b>{$user['name']}</b>,</p>
        <p>The proposal has been <b>approved</b>.</p>

        <p>
            <a href='$proposal_link'
               style='background:#28a745;color:#fff;
               padding:10px 15px;text-decoration:none;
               border-radius:5px;'>
               View Proposal
            </a>
        </p>
        <p>If the button does not work, use this link:</p>
        <p>$proposal_link</p>

        <br>
        <p>Regards,<br>Proposal System</p>
    ";

    $mail->send();
    exit("Proposal approval email sent successfully!");
} catch (Exception $e) {
    exit("Proposal approved, but email sending failed");
}
