<?php
/* SendApprovalOPO.php - Enhanced with Modern Confirmation UI and HTML Email */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;
include('includes/session.inc');
$Title = _('Send OPO for Approval');
include('includes/newheader.php');
include('includes/SQL_CommonFunctions.inc');

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

require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

$userid = $_SESSION['UserID'];

if (isset($_GET['id'])) {
    $_SESSION['id'] = stripslashes($_GET['id']);
}
$opono = $_SESSION['id'];

/* ── Fetch OPO Details ── */
$sql = "SELECT o.*, s.suppname,
    (SELECT COALESCE(SUM(total_price),0) FROM overseas_purchase_orders_details WHERE id=o.id) as total_val,
    (SELECT COUNT(*) FROM overseas_purchase_orders_details WHERE id=o.id) as item_count
    FROM overseas_purchase_orders o
    LEFT JOIN suppliers s ON o.supplier_name = s.supplierid
    WHERE o.id = '" . DB_escape_string($opono) . "'";
$result = DB_query($sql);
$myrow = DB_fetch_array($result);

$suppName = isset($myrow['suppname']) ? $myrow['suppname'] : 'N/A';
$totalVal = isset($myrow['total_val']) ? $myrow['total_val'] : 0;
$itemCount = isset($myrow['item_count']) ? $myrow['item_count'] : 0;
$currency = isset($myrow['currency']) ? $myrow['currency'] : '';
$shipMode = isset($myrow['shipment_mode']) ? $myrow['shipment_mode'] : '';
$status = isset($myrow['status']) ? $myrow['status'] : 'Draft';

/* ── Fetch user email ── */
$EmailSQL = "SELECT email FROM www_users WHERE userid = '" . DB_escape_string($userid) . "'";
$EmailResult = DB_query($EmailSQL);
$myEmail = DB_fetch_array($EmailResult);
$creatorEmail = isset($myEmail['email']) ? $myEmail['email'] : '';

/* ── Process Send if confirmed ── */
$emailSent = false;
$emailError = '';

if(isset($_POST['confirm_send']) AND $_POST['confirm_send'] == '1'){

    $ravinesh = 'rdeo@wormaldfj.com';
    $sharukh = 'msharukh@wormaldfj.com';
    $mosheed = 'mhussein@wormaldfj.com';
    $sachin = 'sachinebusiness@gmail.com';

    // Build professional HTML email body
    $emailBody = '
    <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;background:#fff">
        <div style="background:linear-gradient(135deg,#187278,#2AABB3);padding:24px 32px;border-radius:8px 8px 0 0">
            <h1 style="color:#fff;font-size:20px;margin:0;font-weight:700">Overseas Purchase Order</h1>
            <p style="color:rgba(255,255,255,.8);font-size:13px;margin:6px 0 0">Authorization Required</p>
        </div>
        <div style="padding:24px 32px;border:1px solid #E5E7EB;border-top:none;border-radius:0 0 8px 8px">
            <p style="font-size:14px;color:#1F2937;margin:0 0 16px">A new Overseas Purchase Order requires your authorization:</p>
            <table style="width:100%;border-collapse:collapse;margin:16px 0">
                <tr><td style="padding:8px 12px;background:#F9FAFB;font-size:12px;color:#6B7280;font-weight:600;width:140px;border:1px solid #E5E7EB">OPO Number</td><td style="padding:8px 12px;font-size:14px;font-weight:700;color:#1E8F96;border:1px solid #E5E7EB">#' . $opono . '</td></tr>
                <tr><td style="padding:8px 12px;background:#F9FAFB;font-size:12px;color:#6B7280;font-weight:600;border:1px solid #E5E7EB">Supplier</td><td style="padding:8px 12px;font-size:13px;color:#1F2937;border:1px solid #E5E7EB">' . htmlspecialchars($suppName) . '</td></tr>
                <tr><td style="padding:8px 12px;background:#F9FAFB;font-size:12px;color:#6B7280;font-weight:600;border:1px solid #E5E7EB">Currency</td><td style="padding:8px 12px;font-size:13px;color:#1F2937;border:1px solid #E5E7EB">' . $currency . '</td></tr>
                <tr><td style="padding:8px 12px;background:#F9FAFB;font-size:12px;color:#6B7280;font-weight:600;border:1px solid #E5E7EB">Line Items</td><td style="padding:8px 12px;font-size:13px;color:#1F2937;border:1px solid #E5E7EB">' . $itemCount . ' items</td></tr>
                <tr><td style="padding:8px 12px;background:#F9FAFB;font-size:12px;color:#6B7280;font-weight:600;border:1px solid #E5E7EB">Total Value</td><td style="padding:8px 12px;font-size:14px;font-weight:700;color:#1F2937;border:1px solid #E5E7EB">$' . number_format($totalVal, 2) . '</td></tr>
                <tr><td style="padding:8px 12px;background:#F9FAFB;font-size:12px;color:#6B7280;font-weight:600;border:1px solid #E5E7EB">Shipment Mode</td><td style="padding:8px 12px;font-size:13px;color:#1F2937;border:1px solid #E5E7EB">' . $shipMode . '</td></tr>
                <tr><td style="padding:8px 12px;background:#F9FAFB;font-size:12px;color:#6B7280;font-weight:600;border:1px solid #E5E7EB">Created By</td><td style="padding:8px 12px;font-size:13px;color:#1F2937;border:1px solid #E5E7EB">' . $userid . '</td></tr>
                <tr><td style="padding:8px 12px;background:#F9FAFB;font-size:12px;color:#6B7280;font-weight:600;border:1px solid #E5E7EB">Date</td><td style="padding:8px 12px;font-size:13px;color:#1F2937;border:1px solid #E5E7EB">' . date('d M Y H:i') . '</td></tr>
            </table>
            <p style="font-size:13px;color:#6B7280;margin:16px 0 0">Please log in to the ERP system under <strong>Purchasing → Overseas Purchase Orders</strong> to review and approve this order.</p>
            <div style="margin:20px 0 0;padding:16px 0 0;border-top:1px solid #E5E7EB">
                <p style="font-size:11px;color:#9CA3AF;margin:0">This is an automated email from E-Business ERP System.</p>
            </div>
        </div>
    </div>';

    $EmailSubject = 'OPO #' . $opono . ' - Overseas Purchase Order Requires Authorization (' . $suppName . ')';

    try {
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->Host = 'smtp-relay.sendinblue.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'sachinebusiness@gmail.com';
        $mail->Password = 'R5kyxwrJnWSLH4fh';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        $mail->ClearAddresses();
        $mail->setFrom('erp@ebusinescloudservers.com', 'E-Business ERP');

        $mail->addAddress($sharukh, 'Sharukh Khan');
        $mail->addAddress($mosheed, 'Mosheed Hussein');
        $mail->addAddress($ravinesh, 'Ravinesh Deo');
        $mail->addAddress($sachin, 'Sachin');

        if($creatorEmail){
            $mail->addCC($creatorEmail, $userid);
        }

        $mail->isHTML(true);
        $mail->Subject = $EmailSubject;
        $mail->Body = $emailBody;
        $mail->AltBody = 'Overseas Purchase Order #' . $opono . ' requires your authorization. Supplier: ' . $suppName . ', Total: $' . number_format($totalVal,2) . '. Please log in to ERP to approve.';

        $mail->send();
        $emailSent = true;
    } catch (Exception $e) {
        $emailError = 'Email could not be sent. Error: ' . $mail->ErrorInfo;
    }
}
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>
<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
:root{--opo-primary:#2AABB3;--opo-dark:#1E8F96;--opo-darker:#187278;--opo-light:#E6F7F8;--opo-text:#1F2937;--opo-muted:#6B7280;--opo-border:#E5E7EB;--opo-success:#52C41A;--opo-danger:#FF4D4F;--opo-radius:10px}

.snd-banner{background:linear-gradient(135deg,#187278 0%,#1E8F96 40%,#2AABB3 100%);border-radius:var(--opo-radius);padding:24px 32px 20px;margin:0 0 24px;position:relative;overflow:hidden;font-family:'Poppins',sans-serif}
.snd-banner::before{content:'';position:absolute;top:-50px;right:-30px;width:160px;height:160px;background:rgba(255,255,255,.06);border-radius:50%}
.snd-banner .breadcrumb{display:flex;gap:8px;font-size:12px;color:rgba(255,255,255,.7);margin-bottom:8px}
.snd-banner .breadcrumb a{color:rgba(255,255,255,.7);text-decoration:none}
.snd-banner .breadcrumb a:hover{color:#fff}
.snd-banner h1{color:#fff;font-size:20px;font-weight:700;margin:0;font-family:'Poppins',sans-serif}
.snd-banner h1 i{margin-right:10px;opacity:.9}

.snd-container{max-width:640px;margin:0 auto;padding:0 16px;font-family:'Poppins',sans-serif}

.snd-card{background:#fff;border-radius:var(--opo-radius);border:1px solid var(--opo-border);box-shadow:0 1px 3px rgba(0,0,0,.06);padding:28px 32px;margin-bottom:24px}
.snd-card h2{font-size:15px;font-weight:600;color:var(--opo-text);margin:0 0 4px;display:flex;align-items:center;gap:10px}
.snd-card h2 i{color:var(--opo-primary);font-size:18px}
.snd-card .subtitle{font-size:12px;color:var(--opo-muted);margin-bottom:20px}

.snd-opo-header{display:flex;align-items:center;gap:12px;margin-bottom:20px}
.snd-opo-num{background:var(--opo-light);color:var(--opo-dark);padding:8px 18px;border-radius:8px;font-size:18px;font-weight:700}
.snd-opo-status{display:inline-block;padding:4px 12px;border-radius:12px;font-size:11px;font-weight:600}
.snd-status-draft{background:#FFF7E6;color:#D48806}
.snd-status-approved{background:#E6F7FF;color:#1890FF}

.snd-detail-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:20px}
.snd-detail{padding:14px 16px;background:#F9FAFB;border-radius:8px;border:1px solid var(--opo-border)}
.snd-detail .label{font-size:11px;color:var(--opo-muted);text-transform:uppercase;letter-spacing:.3px;margin-bottom:4px;font-weight:500}
.snd-detail .val{font-size:14px;font-weight:600;color:var(--opo-text)}
.snd-detail .val.highlight{color:var(--opo-dark);font-size:16px}

.snd-recipients{background:#F9FAFB;border-radius:8px;padding:16px 20px;border:1px solid var(--opo-border);margin-bottom:20px}
.snd-recipients h4{font-size:12px;font-weight:600;color:var(--opo-text);margin:0 0 10px;display:flex;align-items:center;gap:6px}
.snd-recipients h4 i{color:var(--opo-primary)}
.snd-recipient{display:flex;align-items:center;gap:8px;padding:6px 0;font-size:12px;color:var(--opo-text)}
.snd-recipient i{color:var(--opo-primary);width:16px;text-align:center}

.snd-actions{display:flex;gap:12px;margin-top:20px}
.snd-btn{padding:10px 24px;border-radius:8px;font-family:'Poppins',sans-serif;font-size:13px;font-weight:600;border:none;cursor:pointer;transition:all .2s;display:inline-flex;align-items:center;gap:8px;text-decoration:none}
.snd-btn-primary{background:var(--opo-primary);color:#fff}
.snd-btn-primary:hover{background:var(--opo-darker);color:#fff}
.snd-btn-outline{background:#fff;color:var(--opo-muted);border:1px solid var(--opo-border)}
.snd-btn-outline:hover{border-color:var(--opo-primary);color:var(--opo-dark)}

.snd-alert{padding:16px 20px;border-radius:8px;font-size:13px;font-weight:500;display:flex;align-items:flex-start;gap:12px;margin-bottom:20px}
.snd-alert-success{background:#F6FFED;color:#389E0D;border:1px solid #B7EB8F}
.snd-alert-error{background:#FFF2F0;color:#CF1322;border:1px solid #FFA39E}
.snd-alert i{font-size:20px;margin-top:1px}

.snd-success-icon{width:64px;height:64px;background:#F6FFED;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 16px}
.snd-success-icon i{font-size:28px;color:var(--opo-success)}
</style>

<div style="padding:0 8px;font-family:'Poppins',sans-serif">

<!-- Banner -->
<div class="snd-banner">
  <div class="breadcrumb">
    <a href="index.php"><i class="fa fa-home"></i> Home</a> <span>›</span>
    <a href="OverseasPurchaseOrders.php">Overseas Purchase Orders</a> <span>›</span>
    <span style="color:#fff">Send for Approval</span>
  </div>
  <h1><i class="fa fa-paper-plane"></i> Send for Approval</h1>
</div>

<div class="snd-container">

<?php if($emailSent){ ?>
  <!-- Success State -->
  <div class="snd-card" style="text-align:center">
    <div class="snd-success-icon"><i class="fa fa-check"></i></div>
    <h2 style="justify-content:center"><i class="fa fa-envelope-circle-check" style="color:var(--opo-success)"></i> Email Sent Successfully</h2>
    <p class="subtitle" style="text-align:center">Approval request for OPO #<?php echo $opono; ?> has been sent to all approvers.</p>
    <div style="margin-top:20px;display:flex;gap:12px;justify-content:center">
      <a href="OverseasPurchaseOrders.php" class="snd-btn snd-btn-primary"><i class="fa fa-arrow-left"></i> Back to Purchase Orders</a>
    </div>
  </div>

<?php } elseif($emailError){ ?>
  <div class="snd-alert snd-alert-error">
    <i class="fa fa-exclamation-circle"></i>
    <div><strong>Email Failed</strong><br><span style="font-size:12px"><?php echo $emailError; ?></span></div>
  </div>
  <div style="text-align:center">
    <a href="OverseasPurchaseOrders.php" class="snd-btn snd-btn-outline"><i class="fa fa-arrow-left"></i> Back</a>
  </div>

<?php } else { ?>
  <!-- Confirmation Form -->
  <div class="snd-card">
    <div class="snd-opo-header">
      <div class="snd-opo-num">#<?php echo $opono; ?></div>
      <?php
        $statusClass = 'snd-status-draft';
        if($status=='Approved') $statusClass = 'snd-status-approved';
      ?>
      <span class="snd-opo-status <?php echo $statusClass; ?>"><?php echo $status; ?></span>
    </div>

    <h2><i class="fa fa-paper-plane"></i> Confirm Approval Request</h2>
    <p class="subtitle">Review the order details below then send for authorization.</p>

    <div class="snd-detail-grid">
      <div class="snd-detail">
        <div class="label">Supplier</div>
        <div class="val"><?php echo $suppName; ?></div>
      </div>
      <div class="snd-detail">
        <div class="label">Currency</div>
        <div class="val"><?php echo $currency; ?></div>
      </div>
      <div class="snd-detail">
        <div class="label">Line Items</div>
        <div class="val"><?php echo $itemCount; ?> items</div>
      </div>
      <div class="snd-detail">
        <div class="label">Total Value</div>
        <div class="val highlight">$<?php echo number_format($totalVal,2); ?></div>
      </div>
      <div class="snd-detail">
        <div class="label">Shipment Mode</div>
        <div class="val"><?php echo $shipMode ? $shipMode : '-'; ?></div>
      </div>
      <div class="snd-detail">
        <div class="label">Entered By</div>
        <div class="val"><?php echo $userid; ?></div>
      </div>
    </div>

    <div class="snd-recipients">
      <h4><i class="fa fa-users"></i> Approval Recipients</h4>
      <div class="snd-recipient"><i class="fa fa-envelope"></i> Sharukh Khan — msharukh@wormaldfj.com</div>
      <div class="snd-recipient"><i class="fa fa-envelope"></i> Mosheed Hussein — mhussein@wormaldfj.com</div>
      <div class="snd-recipient"><i class="fa fa-envelope"></i> Ravinesh Deo — rdeo@wormaldfj.com</div>
      <div class="snd-recipient"><i class="fa fa-envelope"></i> Sachin — sachinebusiness@gmail.com</div>
      <?php if($creatorEmail){ ?>
      <div class="snd-recipient"><i class="fa fa-envelope" style="color:var(--opo-muted)"></i> <span style="color:var(--opo-muted)">CC: <?php echo $userid; ?> — <?php echo $creatorEmail; ?></span></div>
      <?php } ?>
    </div>

    <form method="post" action="SendApprovalOPO.php">
      <input type="hidden" name="confirm_send" value="1"/>
      <div class="snd-actions">
        <button type="submit" class="snd-btn snd-btn-primary" onclick="this.innerHTML='<i class=\'fa fa-spinner fa-spin\'></i> Sending...';this.disabled=true;this.form.submit()">
          <i class="fa fa-paper-plane"></i> Send for Approval
        </button>
        <a href="OverseasPurchaseOrders.php" class="snd-btn snd-btn-outline">
          <i class="fa fa-arrow-left"></i> Cancel
        </a>
      </div>
    </form>
  </div>
<?php } ?>

</div>
</div>

<?php
echo '</div></div></div>';
?>
<div id="m_scroll_top" class="m-scroll-top"><i class="la la-arrow-up"></i></div>
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>
</body>
</html>
