<?php
  /**
   * Coupon
   *
   * @package Digital Downloads Pro
   * @author wojoscripts.com
   * @copyright 2010
   * @version $Id: coupon.php, v2.00 2011-07-10 10:12:05 gewa Exp $
   */
  define("_VALID_PHP", true);
  require_once("../init.php");
?>
<?php
  if (isset($request->post['coupon'])) {
      $coupon = @$request->post['coupon'];
	  $coupon = sanitize($coupon);
      $row2 = $db->first("SELECT sum(price) as total FROM cart WHERE user_id = '" . $db->escape($user->sesid) . "'");
      $row3 = $db->first("SELECT discount, type, minval FROM coupons WHERE code = '" . $db->escape($coupon) . "' AND active = '1'");
      
      if ($row3) {
          if ($row3['minval'] > $row2['total']) {
              print "حـداقـل جمـع از : <strong style=\"color:red\">" . $core->formatMoney($row3['minval']) . "</strong> required";
          } else {
              if ($row3['type'] == 0) {
                  $disc = $row2['total'] / 100 * $row3['discount'];
                  $gtotal = $disc;
              } else {
                  $disc = $row2['total'] - $row3['discount'];
                  $gtotal = $row2['total'] - $disc;
              }
              
              if ($db->first("SELECT coupon FROM extras WHERE user_id = '" . $db->escape($user->sesid) . "'")) {
                  $data['coupon'] = $gtotal;
                  $db->update("extras", $data, "user_id='" . $db->escape($user->sesid) . "'");
              } else {
                  $data['coupon'] = $gtotal;
                  $data['user_id'] = $db->escape($user->sesid);
                  $db->insert("extras", $data);
              }
              
              print "- تخفـیف : <strong style=\"color:green\">" . $core->formatMoney($gtotal) . "</strong>";
          }
      } else {
          print "<span style=\"color:red\"> » کـد نامعتبـر اسـت!</span>";
      }
  }
?>